Nativescript tab page textfield - nativescript

I can't get the value from my bound textfield. I used the tab template. On the Microsoft Android Emulator. Is there something I need to add to the main tab page view model maybe?
View
<GridLayout class="page-content">
<StackLayout orientation="vertical">
<Label class="page-icon fa" text=""></Label>
<TextField id="txtSearch" text="{{ search }}" hint="Search" keyboardType="email" autocorrect="false" autocapitalizationType="none" />
<Button text="Sign in" tap="searchClick" />
</StackLayout>
</GridLayout>
var SearchViewModel = require("./search-view-model");
var svm = new SearchViewModel();
function onLoaded(args) {
var component = args.object;
component.bindingContext = new SearchViewModel();
}
exports.searchClick = function() {
svm.searches()
.catch(function(error) {
console.log(error);
dialogsModule.alert({
message: "Unfortunately we could not find your account.",
okButtonText: "OK"
});
return Promise.reject();
})
.then(function() {
//frameModule.topmost().navigate("views/list/list");
});
};
exports.onLoaded = onLoaded;
model
For some reason viewModel.get("search") returns nothing. The button fires fine.
const observableModule = require("data/observable");
var fetchModule = require("fetch");
//Info is the returning object
function SearchViewModel(info) {
info = info || {};
var viewModel = new observableModule.fromObject({
search: info.search || ""
});
viewModel.searches = function() {
var test = viewModel.get("search");
return fetchModule.fetch(config.apiUrl + viewModel.get("search"), {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then(handleErrors)
.then(function(response) {
return response.json();
})
.then(function(data) {
config.token = data.Result.access_token;
});
};
return viewModel;
}

You can simply use this.search,
Or you can use this.get("search")
Edit: also on a side note,
In your code behind file, you are creating
var svm = new SearchViewModel();
But you are not assigning svm as the bindingContext, instead you are creating a new instance of SearchViewModel. That might cause some unexpected behavior later.

Related

Summernote custom button with dialog

I want to add a custom button to the Summernote toolbar that opens up a dialog that has a textbox for a URL and several checkboxes for settings. I then want to use the info from the dialog to scrape web pages and do processing on the content. The ultimate goal is to place the scraped content into the editor starting where the cursor is. I've searched and found some code on creating a custom button, but not any solid examples of implementing a dialog. I went through the summernote.js code to see how the Insert Image dialog works and that left me really confused. The test code I've got so far is in the code block, below. Thanks in advance to anyone who can help get me sorted out.
var showModalDialog = function(){
alert("Not Implemented");
};
var AddWiki = function(context) {
var ui = $.summernote.ui;
var button = ui.button({
contents: '<i class="fa fa-plus"/> Add Wiki',
tooltip: "Set a New Wiki",
class: "btn-primary",
click: function() {
showModalDialog();
}
});
return button.render();
};
$(".tw-summernote-instance textarea").summernote({
airMode: false,
dialogsInBody: false,
toolbar: [["mybutton", ["customButton"]]],
buttons: {
customButton: AddWiki
},
callbacks: {
onInit: function(e) {
var o = e.toolbar[0];
jQuery(o)
.find("button:first")
.addClass("btn-primary");
}
}
});
I found a good, simple example of what I wanted to do. Here's the code:
(function(factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function($) {
$.extend($.summernote.plugins, {
'synonym': function(context) {
var self = this;
var ui = $.summernote.ui;
var $editor = context.layoutInfo.editor;
var options = context.options;
context.memo('button.synonym', function() {
return ui.button({
contents: '<i class="fa fa-snowflake-o">',
tooltip: 'Create Synonym',
click: context.createInvokeHandler('synonym.showDialog')
}).render();
});
self.initialize = function() {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group">' +
'<label>Add Synonyms (comma - , - seperated</label>' +
'<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
'</div>'
var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';
self.$dialog = ui.dialog({
title: 'Create Synonym',
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
// You should remove elements on `initialize`.
self.destroy = function() {
self.$dialog.remove();
self.$dialog = null;
};
self.showDialog = function() {
self
.openDialog()
.then(function(data) {
ui.hideDialog(self.$dialog);
context.invoke('editor.restoreRange');
self.insertToEditor(data);
console.log("dialog returned: ", data)
})
.fail(function() {
context.invoke('editor.restoreRange');
});
};
self.openDialog = function() {
return $.Deferred(function(deferred) {
var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
var $synonymInput = self.$dialog.find('#input-synonym')[0];
ui.onDialogShown(self.$dialog, function() {
context.triggerEvent('dialog.shown');
$dialogBtn
.click(function(event) {
event.preventDefault();
deferred.resolve({
synonym: $synonymInput.value
});
});
});
ui.onDialogHidden(self.$dialog, function() {
$dialogBtn.off('click');
if (deferred.state() === 'pending') {
deferred.reject();
}
});
ui.showDialog(self.$dialog);
});
};
this.insertToEditor = function(data) {
console.log("synonym: " + data.synonym)
var dataArr = data.synonym.split(',');
var restArr = dataArr.slice(1);
var $elem = $('<span>', {
'data-function': "addSynonym",
'data-options': '[' + restArr.join(',').trim() + ']',
'html': $('<span>', {
'text': dataArr[0],
'css': {
backgroundColor: 'yellow'
}
})
});
context.invoke('editor.insertNode', $elem[0]);
};
}
});
}));

Hide label on buttonclick nativescript

I am trying to make a simple text clicking game to gain a better understanding of Nativescript.
I first have a label with intro text and a question. Then I have 3 buttons to give an answer to the question.
Once the user clicks one of the buttons I want the first label and the 3 buttons to disappear and the next label to appear.
Here is my code:
This is my home-page.js
var frameModule = require("tns-core-modules/ui/frame");
var HomeViewModel = require("./home-view-model");
var homeViewModel = new HomeViewModel();
exports.loaded = function (args) {
var page = args.object;
page.actionBarHidden = true;
page.bindingContext = homeViewModel;
};
exports.SwordButton = function () {
Display1 = false;
Display2 = true;
console.log("The Sword button was pressed");
};
exports.BowButton = function () {
Display1 = false;
Display2 = true;
console.log("The Bow button was pressed");
};
exports.ShieldButton = function () {
Display1 = false;
Display2 = true;
console.log("The Shield button was pressed");
};
This is my home-page.xml:
<ActionBar title="Home" class="action-bar">
</ActionBar>
<StackLayout class="home-panel">
<Label textWrap="true" text="Text game" class="h2 description-label" />
<Label id="text1" textWrap="true" visibility="{{ Display1 ? 'visible' : 'collapsed' }}"
text="It's a zombie apocalypse! You are looting a store when suddenly a zombie bursts in through the door. You frantically search for a weapon. You find a box containing a sword, a bow and a shield. Which one do you choose?"
class="h2 description-label" />
<Label id="text2" textWrap="true" visibility="{{ Display2 ? 'visible' : 'collapsed' }}" text="You chose poorly." />
<Button text="Sword" tap="SwordButton" />
<Button text="Bow" tap="BowButton" />
<Button text="Shield" tap="ShieldButton" />
</StackLayout>
Here is my home-view-model.js:
var observableModule = require("tns-core-modules/data/observable");
function HomeViewModel() {
var weapon;
var viewModel = observableModule.fromObject({
Display1: true,
Display2: false,
textFieldValue: "",
});
return viewModel;
}
module.exports = HomeViewModel;
I hope I have given enough information for you to help, if not please let me know.
Hope you can help.
I fixed it. Turns out I forgot to set the new value of the Display variables.
This is what my new SwordButton function looks like.
exports.SwordButton = function () {
Display1 = false;
Display2 = true;
console.log("The Sword button was pressed");
homeViewModel.set("Display1", Display1);
homeViewModel.set("Display2", Display2);
};
I did the same thing for the BowButton and the ShieldButton functions.

What is NativeScript syntax for list-picker?

I have not been able to find a working example of NS+JS for list-picker, non of the examples in the docs have XML examples.
Can anyone help?
What you’ll need to do is bind a <ListPicker>’s items property to an array on your page’s bindingContext. Here’s a basic example:
<!-- main-page.xml -->
<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded">
<StackLayout>
<ListPicker
items="{{ pokemon }}"
id="pokemonPicker"
></ListPicker>
</StackLayout>
</Page>
// main-page.js
var Observable = require("data/observable").Observable;
var pageData = new Observable({
pokemon: ["Bulbasaur", "Charmander", "Squirtle"]
});
exports.pageLoaded = function(args) {
var page = args.object;
page.bindingContext = pageData;
page.getViewById("pokemonPicker").addEventListener(
Observable.propertyChangeEvent, function(e) {
if (e.propertyName == "selectedIndex") {
console.log("You selected: " + pageData.pokemon[e.value]);
}
}
);
};

How can I pass values loaded by ajax to components?

I'm passing a value as a parameter to a component.
<badge-button params="badge: oarBadge"></badge-button>
Here is the viewModel containing oarBadge:
function AppViewModel() {
var self = this;
self.oarBadge = ko.observable();
$.getJSON('/guy.json', function(data) {
var badge = new Badge('wood oar', data.badges.oar, false);
self.oarBadge(badge);
// self.oarBadge().has() returns true so the badge is being properly created with data
// returned by the ajax call
});
} // AppViewModel()
Here is the Badge constructor:
function Badge(name, has, active) {
var self = this;
self.name = ko.observable(name);
self.has = ko.observable(has);
self.active = ko.observable(active);
self.disabled = ko.computed(function() {
return self.has();
});
self.toggleActive = function() {
self.active(!self.active())
};
self.toggleHas = function() {
self.has(!self.has());
};
}
Here is the component's viewModel:
ko.components.register('badge-button', {
viewModel: function(params) {
var self = this;
self.badge = params.badge();
self.open = function() {
self.badge.toggleHas();
self.badge.toggleActive();
}
},
template:
'<img class="ui image" src="http://fakeimg.pl/300/" data-bind="click: open, css: { disabled: badge.disabled }" >'
});
When the page loads, I get an error telling me that badge is undefined.
Full example: https://gist.github.com/guyjacks/5a8763ff71f90e3fe8b4b153ed9a5283
Try setting a default object before the ajax call is completed, also you should assign the observable itself not the evaluation for the observable, so instead of doing this:
self.badge = params.badge();
You should do it like this:
self.badge = params.badge;
Otherwise your variable won't be updated once the ajax request is completed.
Here is a small example: https://jsfiddle.net/b0bdru1u/1/
Note: As far as I know the disable binding won't work in images

Cant reading from file in nativescrypt

I trying write some strings in file and then read them, but having error message Cannot access a locked file. Tested on iphone and android.
page.xml
<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="pageLoaded" actionBarHidden="true">
<StackLayout>
<Label text="Tap the button" id="label"/>
<Button text="TAP" id="btn" />
</StackLayout>
</Page>
page.js
var frameModule = require("ui/frame");
var view = require("ui/core/view");
var dialogs = require("ui/dialogs");
var fs = require("file-system");
function pageLoaded(args) {
var page = args.object;
var button = view.getViewById(page, "btn");
var label = view.getViewById(page, "label");
button.on("tap", function (){
var documents = fs.knownFolders.documents();
var myFile = documents.getFile("Test_Write.txt");
myFile.writeText("Something")
.then(function () {
myFile.readText()
.then(function (content) {
label.text = content;
}, function (error) {
label.text = error;
});
}, function (error) {
label.text = error;
});
});
}
exports.pageLoaded = pageLoaded;
The write methods lock but never unlock the file.
This has been addressed with the following pull request.

Resources