i'm making a todolist in mootools and having the following problem. i'm store my todo items in a cookie but the issue is i can't read how many cookies i've set so i can get the value of them.
my question is: is there any way to count how many cookies i've so i can loop trough them and get the correct value.
when i put the getData in a console.log i'm getting my json but i also can't read the values from there. what am i doing wrong and wich other implementation do u advise me.
tnx in advance.
for now i've the following code.
window.addEvent('domready', function(){
$('add').addEvent('click', function(){
var value = $('todo').value;
var t = new Todo(value,"beschrijving",new Date(),1);
var storeData = JSON.encode(t);
var c = Cookie.write(value,storeData,{duration:1});
var getData = Cookie.read(value);
console.log(getData);
});
});
var Todo = new Class(
{
initialize: function(title,description,date,isDone){
this.title = title;
this.description = description;
this.date = new Date();
this.isDone = isDone;
},
getTitle:function()
{
return this.title;
},
getIsDone:function()
{
return this.isDone;
},
setIsDone:function(value)
{
this.isDone = value;
},
});
You seem to be missing the core point of cookies - when you set a cookie with a specified name, it overwrites the previous value of that cookie. With your current approach, it will never contain more than a single item.
You have to keep an array of todo items and serialize and store that array instead of the Todo object itself.
Also, you'll grow out of max cookie size quickly this way. I'd recommend using HTML5 LocalStorage instead. A base wrapper of LocalStorage can be found in Mootools Powertools.
Related
I'm using Node-Red and the data is passed using JSON objects.
All of the data is in msg.payload. I want to add a new property, the TimeStamp, to the object without all of this unnecessary code...It works but I know this is sloppy.
Is there a better way?
var TimeStamp = new Date();
var newMsg = [ ];
newMsg.push({payload:
{ TimeStamp:TimeStamp ,
Humidity: msg.payload.Humidity,
Temperature: msg.payload.Temperature,
CO2: msg.payload.CO2,
Light: msg.payload.Light
}
});
return newMsg;
You can add the new property to the existing msg object and pass it on.
msg.payload.TimeStamp = new Date();
return msg;
This is the better approach as it leaves all other message properties untouched.
I am currently trying to figure out how I can retrieve a single value from a sap.ui.model.json.JSONModel
in my main view:
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
};
oController.getConfiguration(getConfigCallback);
console.log(gConfigModel);
in my controller:
getConfiguration : function(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
callback(config);
$.getJSON(sServiceUrl).done(function(data) {
config = data.d;
callback(config);
});
},
In my console.log statement I can see that the data was successfully passed from the backend and successfully set to the JSON model. My requirement is to store the value of attribute Editable in a single variable.
I already tried gConfigModel.getProperty('/'), didnt work. tried to access gConfigModel.oData was undefined .. How can I store it in a single value?
Solution Comment: If you catch data from a backend, you have to take care how long it takes. data can be available later then expected, in my case I added 1s timeout, afterwards I can access the property easily
setTimeout(function() {
console.log(gConfigModel.getProperty('/Editable'));
}, 1000);
I wouldn't advise using the model's getData() method since it is deprecated.
A much better solution is to use gConfigModel.getProperty("/Editable")
(I'm using the root slash here since your property resides in the root of your model)
In the same way, you can also set your data:
gConfigModel.setProperty("/Editable", <your new value>) instead
First of all, thanks for the effort to find solutions of our Problems! (at least, those regarding It stuff.. :) )
I've found a solution which I think is a little bit more save because the timeout is maybe somewhat arbitrary - it would depend on the machine or the amount of data that is to be fetched?
Therefore, I am using an attachRequestCompleted function:
with sUrl_2="path-to-my-service";
var oModel_2 = new sap.ui.model.json.JSONModel(sUrl_2);
oModel_2.attachRequestCompleted(function(data) {
//now, i can access the data stored in the oModel_2, either by getProperty, or by DOM: oModel_2.oData.d.Vendor
gv_selLieferant = oModel_2.getProperty("/d/Vendor");
gv_selEinkOrg = oModel_2.getProperty("/d/PurchOrg");
gv_selEinKGru = oModel_2.getProperty("/d/PurGroup");
});
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m"></script>
<script>
function getConfiguration(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
var data = {
"d": {
"_metadata": "",
"Backup01": "01",
"Editable": "True"
}
};
setTimeout((function() {
config = data;
callback(config);
})(), 2000);
};
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
alert(gConfigModel.getProperty("/d/Editable"));
};
getConfiguration(getConfigCallback);
</script>
Here's what I have mocked out of my MVC code:
$(function(){
var ViewModel = function(){
this.items = ko.observableArray(null);
this.isLoading = ko.observable(true);
};
var data = [{"CreatedAt":"2013-12-29T22:00:20","Intro":"","Body":"","Title":"Test Item","Url":"/news-items/test-item/"},{"CreatedAt":"2013-12-29T21:13:34","Intro":"","Body":"","Title":"Test 1","Url":"/news-items/test-1/"},{"CreatedAt":"2013-12-29T16:03:56","Intro":"","Body":"<p>In the spirit of Christmas we are holding a Christmas photo competition for all members to enter. Prizes will be given to the best Christmas themed photo and the funniest photo. To enter, simply email your photo to: competition#bernese.org.nz. Your entry will be uploaded onto the club's Facebook page where all members can then vote by 'liking' their favourite photo.</p>\n<p>Entries close on the 20th of December and voting will be open until the 5th of January. The winning photo's will be displayed on the website.</p>","Title":"Christmas 2013 Photo Competition","Url":"/news-items/christmas-2013-photo-competition/"}];
var vm = new ViewModel();
ko.applyBindings(vm);
vm.items(test);
vm.isLoading(false);
})
I have mocked it from my MVC code, but the data object is basically what was returned from my controller. Knockout mapping is not working in this case and I suspect it's the way my data is returned. Is this a valid way, or do I need to wrap it in a DTO of sorts, e.g.: { items: [{item1:'...'},{item2:'...'}]}?
Thanks.
EDIT:
My mistake, I already defined items as observableArray. I use it this way so as soon as the page loads the loader gif is displayed. I have done it this way before, the only difference this time being the format of the json returned.
ADDED: Here's the example
I don't know if this is the only problem, but
this.items = ko.observable(null);
should be
this.items = ko.observableArray();
But I probably do the whole thing more like
$(function(){
var ViewModel = function(items){
this.items = ko.observableArray(items);
};
var data = [...];
var vm = new ViewModel(data);
})
UPDATE: Here is a fully working jsfiddle
The ko.mapping.fromJS(data) returns a ko.observableArray if the data parameter is already an array.
So you need to unwrap the returned ko.observableArray before assigning it:
var vm = new ViewModel();
ko.applyBindings(vm);
var test = ko.mapping.fromJS(data);
vm.items(test()); // you need to write `test()` to get the underlaying array.
Or you can directly fill in your already declared ko.observableArray with writing:
var vm = new ViewModel();
ko.applyBindings(vm);
ko.mapping.fromJS(data, {} /* mapping options */, vm.items);
Here is your updated JSFiddle.
I'm using the following code to load all Json data.
$.getJSON("/Home/GetSortedLists", function (allData) {
var mappedSortedLists = $.map(allData, function (item) { return new SortedLists(item) });
viewModel.sortedlists(mappedSortedLists);
});
I also need to load a single record from the same Json data; the record with the highest SortedListsID value (i.e. the last record entered).
Can anybody suggest the best way to do this? I've considered adding viewModel.lastsortedlist and amending the above code somehow. I've also considered creating a last custom binding to do something like:
<tbody data-bind="last: sortedlists.SortedListID">
All advice welcome.
Unless you want to do more ui-related stuff with the record, I don't think you need the custom binding.
It should be enough to compute it in the getJSON callback and save it in the viewModel:
$.getJSON("/Home/GetSortedLists", function (allData) {
var mappedSortedLists = $.map(allData, function (item) { return new SortedLists(item) });
viewModel.sortedlists(mappedSortedLists);
//correct the sort function if it's bad, or drop it if allData is already sorted
var sortedData = allData.sort(function(a,b){ return a.SortedListID - b.SortedListID})
viewModel.lastSortedList(sortedData[sortedData.length - 1])
});
Or, if it can change outside the getJSON callback, you could also make it a computed observable:
viewModel.lastSortedList = ko.computed(function(){
//correct the sort function if it's bad, or drop it
var sortedData = mappedSortedLists().sort(function(a,b){ return a.SortedListID - b.SortedListID})
return sortedData[sortedData.length - 1]
}, this)
i use fetch from backbone.js to load a json model but success will not hit.
var DialogModel = Backbone.Model.extend({
url : function() {
return '/messages/getDialog';
},
parse : function(res) {
return res.dialog;
}
});
var DialogView = Backbone.View.extend({
el: $("#page"),
initialize: function() {
var onDataHandler = function() {
this.render();
};
this.model = new DialogModel();
this.model.fetch({ success : onDataHandler});
},
render: function(){
var data = {
dialogModel : this.model
};
var form = new Backbone.Form({
model: data
});
$(this.el).html(form.render().el);
}
});
What happens now:
DialogView initialize is called.
this.model.fetch is called but the onDataHandler function will not be hit if success.
/messages/getDialog throws a json file back.
The json file is loading well as i can see in the network browser.
Thanks for your help!
Oleg
The problem you're having is due to a typical JS gotcha and not related to Backbone itself. Try
var that = this;
this.model.fetch({
success : function () {
that.render();
}
});
The way you're currently passing onDataHandler is problematic as it will cause this to refer to the global object instead of the DialogView, when the function is called.
This fiddle demonstrates the problematic version vs one that works.
(You may also want to take a look at JS strict mode which can shield you from this type of errors.)
Even better is to listen for an event:
this.model.on("sync", this.render).fetch();
I ran across this question while looking for something else, but the currently accepted answer drives me nuts. There's no good reason to be sprinkling this and that all over your code. Backbone (underscore) includes a context parameter that you can bind to.
that = this makes no sense. If you must implement obsolete 2007-era Crockford patterns, then say var self = this. Saying that = this is like saying left = right. Everyone Stop.