What I want to achieve is to create subscription for model properties. This subscription function should call WebApi via Ajax updating property value in database. For ajax call I need three paramaters: "fieldName", "fieldValue" and "modelId", ajax will update database row based on those three parameters.
I have many properties and all of them need the same functionality, so I do not want to subscribe for each property individually, so I found a following suggestion:
ko.subscribable.fn.withUpdater = function (handler) {
var self = this;
this.subscribe(handler);
//support chaining
return this;
};
Add this is how it is "attached" to observables:
self.ModelId= ko.observable();
self.CompanyName = ko.observable().withUpdater(update);
where update is some js function outside model.
However, I have problem, because I am not able to pass three paramaters to update functions (or also I can say in another words - I need to be able to get viewModel.ModelId property value inside update, as well as propertyName).
function update (propertyName, propertyNewValue, anotherPropertyValue) {
//do ajax update
}
As an example for CompanyName property it will be:
update("CompanyName", "New Company value here", 3),
where
3 == viewModel.ModelId
There might be a better way to do this, but the following will work:
First, add a target object to the withUpdate method:
ko.subscribable.fn.withUpdater = function (handler, target, propname) {
var self = this;
var _oldValue;
this.subscribe(function (oldValue) {
_oldValue = oldValue;
}, null, 'beforeChange');
this.subscribe(function (newValue) {
handler.call(target, _oldValue, newValue, propname);
});
return this;
};
The update subscribe function will get scoped to the target property:
var update = function (propertyName) {
console.log('propname is '+ propname + ' old val: ' + oldvalue + ', new val: ' + newvalue + ', model id: ' + this.ModelId());
}
Now you will need to use it a little differently.
self.CompanyName = ko.observable().withUpdater(update, self, "CompanyName");
An example http://plnkr.co/edit/HhbKEm?p=preview
I couldn't get the scope of the withUpdater function to be that of the object without explicitly passing in the target and a string for the company name.
You can declare your function as a variable outside of the 'fn' scope.
var dataservice = 'my class that has the data calls';
var altFunc = function () {
return ko.pureComputed(function () {
var currentItem = this().filter(function (item) {
// Do knockout stuff here and return your data
// also make calls to the dataservice class
}, this, dataservice);
};
ko.observableArray.fn.someNewFunctionality = altFunc;
Related
In my Ionic app I've added the plugin 'ngStorage' and it comes with a little demo code:
var add = function (thing) {
$localStorage.things.push(thing);
}
This works exactly as told. I add("foo") it, and do getAll() and the value is there. I remove the add(), but keep the getAll(), I still have the value "foo" (as expected).
This isn't very usefull for me, I want to access it with keys, so I've made the following:
var addByKey = function (key, value) {
$localStorage.things[key] = value;
// Or, I've also tried:
$localStorage.things.key = value;
}
When I do the addByKey("foo","bar") and then the getAll() I get the values exactly as I want. When I remove the addByKey() and reload, I expect it to still remember the set information, but it doesn't exist. However, the first attempt via the add() function still exists, "foo" is still there (meaning the array doesnt reset).
How do I make a key->value type of structure?
In case it's usefull:
.factory ('StorageService', function ($localStorage) {
$localStorage = $localStorage.$default({
things: []
});
var _getAll = function () {
return $localStorage.things;
};
var _add = function (thing) {
$localStorage.things.push(thing);
}
var _addByKey = function (thing, value) {
$localStorage.things[key] = value;
// Or, I've also tried:
$localStorage.things.key = value;
}
return {
getAll: _getAll,
add: _add,
addByKey: _addByKey
};
})
Assuming that you want a key value storage system you can simply use an object instead of an array so that every key can be set as a property of this object.
.factory('StorageService', function($localStorage) {
$localStorage = $localStorage.$default({
things: {}
});
var _getAll = function() {
return $localStorage.things;
};
var _addByKey = function(thing, value) {
$localStorage.things[thing] = value;
}
return {
getAll: _getAll,
addByKey: _addByKey
};
})
However, assuming that you want to keep a reference of all values on the main collection and access them through keys, you can consider using an object to store the things intead of an array. So that you can use a property to store all items (you can store in a different place as well) and use this object to store your keys by referencing the to a desired value on your collection.
You may need to implement the deletion logic to maintain the consistence between the collection and the dictionary.
Your factory would look like this:
.factory('StorageService', function($localStorage) {
$localStorage = $localStorage.$default({
things: {
items: []
}
});
var _getAll = function() {
return $localStorage.things.items;
};
var _add = function(thing) {
$localStorage.things.items.push(thing);
}
var _addByKey = function(thing, value) {
var i = $localStorage.things.items.push(value) - 1;
$localStorage.things[thing] = $localStorage.things.items[i];
}
return {
getAll: _getAll,
add: _add,
addByKey: _addByKey
};
})
trying to get my head around objects, methods, closures, etc... in Javascript.
Can't see why this isn't working, some fundamental flaw in my thinking I guess. I'm expecting the val variable to be passed through to the addNote() function but it isn't. I thought that any variables declared outside of a function are available to that function, as long as they're not within another function. Is that not correct?
if(typeof(Storage) !== "undefined") {
console.log(localStorage);
var $input = $('#input'),
$submit = $('#submit'),
$list = $('#list'),
val = $input.val();
var noteApp = {
addNote : function(val) {
var item = val.wrap('<li />');
item.appendTo($list);
clearField();
},
clearField : function() {
$input.val = '';
},
delNote : function(note) {
}
};
$submit.on('click', function(){
noteApp.addNote();
});
} else {
}
I'm trying to learn how the pros manage to get their code so clean, concise and modular. I figured a note app would be a perfect start, shame I got stuck at the first hurdle...
Cheers.
There are several issues with the code in the question
defining an argument named val and not passing an argument to the function
when calling clearField() inside the object literal it's this.clearField()
You're only getting the value once, not on every click
val is a string, it has no wrap method
$input.val = ''; is not valid jQuery
I would clean it up like this
var noteApp = {
init: function() {
if (this.hasStorage) {
this.elements().events();
}
},
elements: function() {
this.input = $('#input');
this.submit = $('#submit');
this.list = $('#list');
return this;
},
events: function() {
var self = this;
this.submit.on('click', function(){
self.addNote();
});
},
hasStorage: (function() {
return typeof(Storage) !== "undefined";
})(),
addNote: function() {
this.list.append('<li>' + this.input.val() + '</li>');
this.clearField();
return this;
},
clearField: function() {
this.input.val('');
},
delNote : function(note) {
}
}
FIDDLE
Remember to call the init method
$(function() { noteApp.init(); });
In your call to addNote(), you don't pass any argument for the val, so it will be undefined:
noteApp.addNote();
// ^^ nothing
Pass the input (seems you want the jQuery object not the string value because of your val.wrap call):
noteApp.addNote($input);
When you declare the val in the function, it is scoped to that function and will only be populated if the function call passes a value for that argument. Even if you have another variable in an upper scope with the same name val, they are still differentiated. Any reference to val in the function will refer to the local val not the upper scope.
I'm just wondering how to remove a property from knockout viewModel. Specifically, a computed one. I have a simple viewModel
function viewModel(){
var self = this;
self.name = ko.observable("John");
self.lastname = ko.observable("Doe");
self.age = ko.observable("22");
self.fullName = ko.computed(function(){
return self.name() + self.lastname();
});
self.fullNameAndAge = ko.computed(function(){
return self.name() + self.lastname() + ': ' + self.age();
});
};
The data is going to be sent to the server, but I want to exclude the computed data from the viewModel.
I thought something like this would get all the computed data and remove it, but didn't find anything like it.
for (observableKey in viewModel) {
if (ko.isComputed(viewModel[observableKey])
{
delete viewModel[observableKey];
}
}
Knockout can return a regular object from which you then can remove anything you want.
var plainJs = ko.toJS(viewModel);
delete plainJs.fullName;
Documented here.
You can loop through keys like this:
for (var key in obj) {
if(ko.isComputed(obj[key]))
{
delete obj[key];
}
}
EDIT
Here is a working fiddle.In fiddle click over the button and check the console, there you can see 2 objects, first one is before removing computed obervables and second one is after removing computed observables.
My preferred approach for this sort of problem is to create a specific transport object for whatever your JSON call requires.
var userSaveRequest = function(data) {
var self = this;
self.name = data.name;
self.lastname = data.lastname;
// etc, etc
}
Then, from my calling code, something like this to get the JSON.
// inside viewModel
self.saveUser = function(){
var queryData = ko.mapping.toJSON(
new userSaveRequest(ko.mapping.toJS(self))
);
// use querydata in AJAX
}
Also, it's worth remembering just how damn flexible Javascript is. You can create an object of your own design on the fly if need be.
var queryData = ko.mapping.toJSON(
{
name: self.name(),
lastname: self.lastname()
}
);
I'm binding data to a page using KnockoutJS, the ViewModel is being populated by an JSON response from an AJAX call using the mapping plugin, like this:
$(function () {
$.getJSON("#Url.Action("Get")",
function(allData) {
viewModel = ko.mapping.fromJS(allData);
viewModel.Brokers.Url = ko.computed(function()
{
return 'BASEURLHERE/' + this.BrokerNum();
});
ko.applyBindings(viewModel);
});
});
The middle part there doesn't work (it works fine without that computed property). "Brokers" is an observable array, and I want to add a computed value to every element in the array called URL. I'm binding that Brokers array to a foreach, and I'd like to use that URL as the href attribute of an anchor. Any ideas?
I've been working through very similar issues and I've found that you can intercept the creation of the Broker objects and insert your own fields using the mapping options parameter:
var data = { "Brokers":[{"BrokerNum": "2"},{"BrokerNum": "10"}] };
var mappingOptions = {
'Brokers': {
create: function(options) {
return (new (function() {
this.Url = ko.computed(function() {
return 'http://BASEURLHERE/' + this.BrokerNum();
}, this);
ko.mapping.fromJS(options.data, {}, this); // continue the std mapping
})());
}
}
};
viewModel = ko.mapping.fromJS(data, mappingOptions);
ko.applyBindings(viewModel);
Here is a fiddle to demonstrate this: http://jsfiddle.net/pwiles/ZP2pg/
Well, if you want Url in each broker, you have to add it to each broker:
$.each(viewModel.Brokers(), function(index, broker){
broker.Url = ko.computed(function(){return 'BASEURLHERE/' + broker.BrokerNum();});
});
I guess BrokerNum is not going to change, so you might as well just calculate Url once:
$.each(viewModel.Brokers(), function(index, broker){
broker.Url = 'BASEURLHERE/' + broker.BrokerNum();
});
You can also add Url property during mapping by providing "create" callback to ko.mapping.fromJS function. See mapping plugin docs for details.
If you only need url to bind to href, just bind the expression in html (within foreach binding):
<a data-bind="attr: {href: 'BASEURLHERE/' + BrokerNum()}">link to broker details</a>
Thanks to Peter Wiles i have very similar solution:
var ViewModel = function (data, ranges) {
var self = this;
this.productList = ko.observableArray();
var productListMapping = {
create: function (options) {
return (new (function () {
//this row above i don't understand...
this.len = ko.computed(function () {
//just test function returning lenght of object name
// and one property of this model
return this.name().length + ' ' + self.cons_slider_1();
}, this);
ko.mapping.fromJS(options.data, {}, this); // continue the std mapping
})());
}
}
this.cons_slider_1 = ko.observable(100);
ko.mapping.fromJS(data, productListMapping, this.productList);
};
Some differences:
I am not mapping to self, but on this.product.
The input json has not parent name like 'Brokers' in above example:
var products = [
{ "id": "pp1", "name": "Blue windy" },
{ "id": "pp1", "name": "Blue windy" }];
So in productMapping i'm typing just 'create:'
But, what i do not understand is the structure of create function. Could somebody explain me why the function returns new function, which has property. Couldn't it be simplified somehow?
I am new to knockoutjs and I have an uber-basic question for you:
I have been able to successfully subscribe to a user changing the on screen twitter handle AND successfully fetch the tweets and display the last recent tweet of a user using console.log(json.results[0].text); However I am not confident that my observable array is working, when I push the json.results into recent tweets: recent_tweets.push(json.results[0].text) I see an [] empty array.
What is going on? Is logging ko.observable array possible?
console.log("TwitterFeedComponent loaded")
TwitterFeedComponent = function(attributes) {
if (arguments[0] === inheriting)
return;
console.log("TwitterFeedComponent() loaded")
var component = this;
var url = 'https://twitter.com/search.json?callback=?';
this.attributes.twitter_user_handle.subscribe(function(value) {
alert("the new value of the twitter handle is " + value);
console.log("I have loaded")
var url = 'https://twitter.com/search.json?callback=?';
var twitter_parameters = {
include_entities: true,
include_rts: true,
q: 'from:' + value,
count: '3'
}
$.getJSON(url,twitter_parameters,
function(json) {
result = json.results[0].text
recent_tweets.push(json.results[0].text);
console.log(recent_tweets);
console.log(json.results[0].text);
});
});
};
To access the actual values of an observable whether it's an array or not you need include parenthesis. For example the following will work:
var recent_tweets= ko.observableArray(["hello", "hi", "how are you"]);
console.log(recent_tweets());
The same is true when assigning variables.
Here is an example of a regular scalar value:
var myObservableName = ko.observable("Luis");
myObservableName("Dany"); // changes the name to: Dany
var Name = myObservableName(); // gets the value and assigns it to the variable Name (in this case the value is "Dany")
To answer this a little differently, you could always use Knockout's subscribe() functionality. Let's assume you have the following view-model:
App.MyViewModel = function() {
var self = this;
self.TestProperty = ko.observable(null);
}
For demonstrations sake, let's assume this property is bound to a text field, as follows:
<input type="text" id="TestPropertyField" data-bind="textInput: TestProperty" />
Now let's assume that you'd like to log any time this value changes. To do this, simply update your view-model as follows:
App.MyViewModel = function() {
var self = this;
self.TestProperty = ko.observable(null);
self.TestProperty.subscribe(function(newValue){
console.log("The new value is: " + newValue);
});
}