Access property of model on change event in backbone.js - javascript

Just started Backbone.js and following tuorials at backbonejs.org.
Here is what I wanted to achieve. I created a model which asks for width and saves it. Now I have used listenTo with object I have created as below on model to read the changed property value. It triggered the change event, but, I always get undefined for width. Code is below.
var mod = Backbone.Model.extend({
askColor:function() {
var w = prompt("Enter width");
this.set({ width:w})
}
});
var model = new mod();
model.set({width:1234})
var obj = {};
_.extend(obj,Backbone.Events);
obj.listenTo(model, 'change', function() {
alert("width = "+model.width)
})
model.askColor();
I really don't know what am I missing in the code or am I doing wrong? Please help out a beginner....

The width attribute is actually stored inside model.attributes. You should use .get() to get the width attribute.
obj.listenTo(model, 'change', function() {
alert("width = "+model.get('width'))
})

You can also use model.attributes.width alongwith model.get('width').
Also following is the best tutorial I found when I started to learn Backbone.js:
http://adrianmejia.com/blog/2012/09/11/backbone-dot-js-for-absolute-beginners-getting-started/

Related

Calling function on custom event in javascript

i want to bind an event handler to my (dynamic) javascript object, but it doesnt work how i think.
Do you have an idea how i could solve it?
What i want is to call an object function on a custom event. Or in other words i want to bind an event listener to an update function of my object.
For example i have my demo object:
var Demo = function (name) {
this.name = name;
var eventCounter = 0;
this.updateCounter = function () {
eventCounter++;
}
//...
};
Then i create multiple dynamic instances from it, like for example
var names = ["Jon", "Doe", "Max", "Mustermann"]
for(var i in names) {
new Demo(names[i])
}
and sometimes i want to update this Demo instance with a custom event.
document.dispatchEvent(new CustomEvent("CUSTOMEVENT"));
so my question is, how can i achieve something like the following
document.addEventListener("CUSTOMEVENT", function(){
// how to get the dynamic Demo instance?
// i want something like Demo.updateCounter()
});
My idea was to push the demo object into an array like
var names = ["Jon", "Doe", "Max", "Mustermann"]
var elementsToUpdate = [];
for(var i in names) {
elementsToUpdate[i] = new Demo(names[i])
}
and then in the event listener i can access them by
document.addEventListener("CUSTOMEVENT", function(){
elementsToUpdate[i].updateCounter()
});
But it feels a little ugly to me. So maybe there is a better solution for updating a dynamic instance of an object.
Thanks in advance

How do I use fetched backbone collection data in another view?

Trying to learn Backbone and hitting a stumbling block when trying to fetch data, I fetch the data fine from with my view SearchBarView but once the data has been fetched I don't know how I can get this data in my SearchResultsView in order to template out each result?
Sorry if this sounds a little vague, struggling to get my head around this at the moment so could do with the guidance!
SearchBarView
performSearch: function(searchTerm) {
// So trim any whitespace to make sure the word being used in the search is totally correct
var search = $.trim(searchTerm);
// Quick check if the search is empty then do nothing
if(search.length <= 0) {
return false;
}
// Make the fetch using our search term
dataStore.videos.getVideos(searchTerm);
},
Goes off to VideoSearchCollection
getVideos: function(searchTerm) {
console.log('Videos:getVideos', searchTerm);
// Update the search term property which will then be updated when the url method is run
// Note make sure any url changes are made BEFORE calling fetch
this.searchTerm = searchTerm;
this.fetch();
},
SearchResultsView
initialize: function() {
// listens to a change in the collection by the sync event and calls the render method
this.listenTo(this.collection, 'sync', this.render);
console.log('This collection should look like this: ', this.collection);
},
render: function() {
var self = this,
gridFragment = this.createItems();
this.$el.html(gridFragment);
return this;
},
createItems: function() {
var self = this,
gridFragment = document.createDocumentFragment();
this.collection.each(function (video) {
var searchResultView = new SearchResultView({
'model': video
});
gridFragment.appendChild(searchResultView.el);
}, this);
return gridFragment;
}
Now I'm not sure how I can get this data within SearchResultView, I think I need to trigger an event from somewhere and listen for the event in the initialize function but I'm not sure where I make this trigger or if the trigger is made automatically.
Solution 1
If dataStore is a global variable then
SearchBarView
dataStore - appears like a global variable
videos - a collection attached to global variable
then in
SearchResultsView
this.listenTo(dataStore.videos, 'sync', this.render);
Solution 2
If dataStore is not a global variable
getVideos: function(searchTerm) {
console.log('Videos:getVideos', searchTerm);
// Update the search term property which will then be updated when the url method is run
// Note make sure any url changes are made BEFORE calling fetch
this.searchTerm = searchTerm;
var coll=this; //this should refer to the collection itself
this.fetch().done(function(){
var searchResultView = new SearchResultsView({collection:coll});
searchResultView.render();
});
},
It is not 100% clear how you are initializing your SearchResultView.
But, in order to have reference to the collection, can't you simply pass in the reference to the constructor of the view. Something like this:
// In your SearchbarView
var myCollection = new Backbone.Collection(); // and you are populating the collection somewhere somehow
var searchResultView = new SearchResultView(myCollection) // you just pass this collection as argument.
myCollection.bind("change", function(){
searchResultView.parentCollection = myCollection;
}
And inside your searchResultView you just refer this collection by parentCollection for instance.
If you make it more explicit as in how these 2 views are connected or related, I may be able to help you more. But, with given info, this seems like the easiest way.

GUI Layer on limeJS

I'm working with limeJS trying to figure out the best way to put a GUI over limeJS. Here's a better explanation:
I've created two classes, one called 'SceneWithGui' and another called 'GuiOverlay'. My intention is that 'SceneWithGui' inherits from 'lime.Scene', adding a property and two methods:
guiLayer (which is a GuiOverlay object)
setGuiLayer
getGuiLayer
As follows:
//set main namespace
goog.provide('tictacawesome.SceneWithGui');
//get requirements
goog.require('lime.Scene');
goog.require('tictacawesome.GuiOverlay');
tictacawesome.SceneWithGui = function() {
lime.Node.call(this);
this.guiLayer = {};
};
goog.inherits(tictacawesome.SceneWithGui, lime.Scene);
tictacawesome.SceneWithGui.prototype.setGuiLayer = function (domElement){
this.guiLayer = new tictacawesome.GuiOverlay(domElement);
};
tictacawesome.SceneWithGui.prototype.getGuiLayer = function (){
return this.guiLayer;
};
The intention with 'GuiOverlay' is to make it hold the DOM element in a way that when the Scene or the Director get resized, it will too. For it, I just inherited from 'lime.Node', hoping it is something already set on it. My code:
//set main namespace
goog.provide('tictacawesome.GuiOverlay');
//get requirements
goog.require('lime.Node');
tictacawesome.GuiOverlay = function(domElement){
lime.Node.call(this);
this.setRenderer(lime.Renderer.DOM);
this.domElement = domElement;
};
goog.inherits(tictacawesome.GuiOverlay, lime.Node);
And that's basically the idea of it all. For better visualization, here's a sample use:
//set main namespace
goog.provide('tictacawesome.menuscreen');
//get requirements
goog.require('lime.Director');
goog.require('lime.Scene');
goog.require('lime.Layer');
goog.require('lime.Sprite');
goog.require('lime.Label');
goog.require('tictacawesome.SceneWithGui');
tictacawesome.menuscreen = function(guiLayer) {
goog.base(this);
this.setSize(1024,768).setRenderer(lime.Renderer.DOM);
var backLayer = new lime.Layer().setAnchorPoint(0, 0).setSize(1024,768),
uiLayer = new lime.Layer().setAnchorPoint(0, 0).setSize(1024,768),
backSprite = new lime.Sprite().setAnchorPoint(0, 0).setSize(1024,768).setFill('assets/background.png');
backLayer.appendChild(backSprite);
this.appendChild(backLayer);
lime.Label.installFont('Metal', 'assets/metalang.ttf');
var title = new lime.Label().
setText('TicTacAwesome').
setFontColor('#CCCCCC').
setFontSize(50).
setPosition(1024/2, 100).setFontFamily('Metal');
uiLayer.appendChild(title);
this.appendChild(uiLayer);
this.setGuiLayer(guiLayer);
};
goog.inherits(tictacawesome.menuscreen, tictacawesome.SceneWithGui);
It all looks pretty on code, but it just doesn't work (the scene doesn't even get displayed anymore). Here are the errors I'm getting through Chrome console:
Uncaught TypeError: Cannot read property 'style' of undefined
director.js:301
Uncaught TypeError: Cannot read property
'transform_cache_' of undefined
I'm not really experienced in JS, so the only clue I found is that this happens when 'tictacawesome.menuscreen' reaches 'goog.base(this)'.
UPDATE: After some messing with the code, I'm able to pass the previous problems I had (before this edit), and now I stumble on the ones cited above. When it reaches directior.js:301, the line is scene.domElement.style['display']='none';. scene exists, but scene.domElement doesn't. Did I somehow fucked up the domElement with my guiOverlay?
Any ideas? Any obvious flaws on my design? Am I on the right path?
Thanks.
Your SceneWithGui extends lime.Scene but you call lime.Node.call(this); in SceneWithGui.
The code in SceneWithGui should look like this:
//set main namespace
goog.provide('tictacawesome.SceneWithGui');
//get requirements
goog.require('lime.Scene');
goog.require('tictacawesome.GuiOverlay');
tictacawesome.SceneWithGui = function() {
lime.Scene.call(this);//This was lime.Node.call(this);
this.guiLayer = {};
};
goog.inherits(tictacawesome.SceneWithGui, lime.Scene);
tictacawesome.SceneWithGui.prototype.setGuiLayer = function (domElement){
this.guiLayer = new tictacawesome.GuiOverlay(domElement);
};
tictacawesome.SceneWithGui.prototype.getGuiLayer = function (){
return this.guiLayer;
};
Can find it out quite quickly when creating a normal scene with var scene = new lime.Scene() breakpoint at that line and stepping into it.
It'll take you to scene.js and then set a breakpoint at lime.Node.call(this);
Then you would have noticed when creating scene = new tictacawesome.menuscreen(); that that breakpoint never hits.

Functional object basics. How to go beyond simple containers?

On the upside I'm kinda bright, on the downside I'm wracked with ADD. If I have a simple example, that fits with what I already understand, I get it. I hope someone here can help me get it.
I've got a page that, on an interval, polls a server, processes the data, stores it in an object, and displays it in a div. It is using global variables, and outputing to a div defined in my html. I have to get it into an object so I can create multiple instances, pointed at different servers, and managing their data seperately.
My code is basically structured like this...
HTML...
<div id="server_output" class="data_div"></div>
JavaScript...
// globals
var server_url = "http://some.net/address?client=Some+Client";
var data = new Object();
var since_record_id;
var interval_id;
// window onload
window.onload(){
getRecent();
interval_id = setInterval(function(){
pollForNew();
}, 300000);
}
function getRecent(){
var url = server_url + '&recent=20';
// do stuff that relies on globals
// and literal reference to "server_output" div.
}
function pollForNew(){
var url = server_url + '&since_record_id=' + since_record_id;
// again dealing with globals and "server_output".
}
How would I go about formatting that into an object with the globals defined as attributes, and member functions(?) Preferably one that builds its own output div on creation, and returns a reference to it. So I could do something like...
dataOne = new MyDataDiv('http://address/?client');
dataOne.style.left = "30px";
dataTwo = new MyDataDiv('http://different/?client');
dataTwo.style.left = "500px";
My code is actually much more convoluted than this, but I think if I could understand this, I could apply it to what I've already got. If there is anything I've asked for that just isn't possible please tell me. I intend to figure this out, and will. Just typing out the question has helped my ADD addled mind get a better handle on what I'm actually trying to do.
As always... Any help is help.
Thanks
Skip
UPDATE:
I've already got this...
$("body").prepend("<div>text</div>");
this.test = document.body.firstChild;
this.test.style.backgroundColor = "blue";
That's a div created in code, and a reference that can be returned. Stick it in a function, it works.
UPDATE AGAIN:
I've got draggable popups created and manipulated as objects with one prototype function. Here's the fiddle. That's my first fiddle! The popups are key to my project, and from what I've learned the data functionality will come easy.
This is pretty close:
// globals
var pairs = {
{ div : 'div1', url : 'http://some.net/address?client=Some+Client' } ,
{ div : 'div2', url : 'http://some.net/otheraddress?client=Some+Client' } ,
};
var since_record_id; //?? not sure what this is
var intervals = [];
// window onload
window.onload(){ // I don't think this is gonna work
for(var i; i<pairs.length; i++) {
getRecent(pairs[i]);
intervals.push(setInterval(function(){
pollForNew(map[i]);
}, 300000));
}
}
function getRecent(map){
var url = map.url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
function pollForNew(map){
var url = map.url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
and the html obviously needs two divs:
<div id='div1' class='data_div'></div>
<div id='div2' class='data_div'></div>
Your 'window.onload` - I don't think that's gonna work, but maybe you have it set up correctly and didn't want to bother putting in all the code.
About my suggested code - it defines an array in the global scope, an array of objects. Each object is a map, a dictionary if you like. These are the params for each div. It supplies the div id, and the url stub. If you have other params that vary according to div, put them in the map.
Then, call getRecent() once for each map object. Inside the function you can unwrap the map object and get at its parameters.
You also want to set up that interval within the loop, using the same parameterization. I myself would prefer to use setTimeout(), but that's just me.
You need to supply the loadResource() function that accepts a URL (string) and returns the HTML available at that URL.
This solves the problem of modularity, but it is not "an object" or class-based approach to the problem. I'm not sure why you'd want one with such a simple task. Here's a crack an an object that does what you want:
(function() {
var getRecent = function(url, div){
url = url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(div);
elt.innerHTML = content;
}
var pollForNew = function(url, div){
url = url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(div);
elt.innerHTML = content;
}
UpdatingDataDiv = function(map) {
if (! (this instanceof arguments.callee) ) {
var error = new Error("you must use new to instantiate this class");
error.source = "UpdatingDataDiv";
throw error;
}
this.url = map.url;
this.div = map.div;
this.interval = map.interval || 30000; // default 30s
var self = this;
getRecent(this.url, this.div);
this.intervalId = setInterval(function(){
pollForNew(self.url, self.div);
}, this.interval);
};
UpdatingDataDiv.prototype.cancel = function() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
})();
var d1= new UpdatingDataDiv('div1','http://some.net/address?client=Some+Client');
var d2= new UpdatingDataDiv('div2','http://some.net/otheraddress?client=Some+Client');
...
d1.cancel();
But there's not a lot you can do with d1 and d2. You can invoke cancel() to stop the updating. I guess you could add more functions to extend its capability.
OK, figured out what I needed. It's pretty straight forward.
First off disregard window.onload, the object is defined as a function and when you instantiate a new object it runs the function. Do your setup in the function.
Second, for global variables that you wish to make local to your object, simply define them as this.variable_name; within the object. Those variables are visible throughout the object, and its member functions.
Third, define your member functions as object.prototype.function = function(){};
Fourth, for my case, the object function should return this; This allows regular program flow to examine the variables of the object using dot notation.
This is the answer I was looking for. It takes my non-functional example code, and repackages it as an object...
function ServerObject(url){
// global to the object
this.server_url = url;
this.data = new Object();
this.since_record_id;
this.interval_id;
// do the onload functions
this.getRecent();
this.interval_id = setInterval(function(){
this.pollForNew();
}, 300000);
// do other stuff to setup the object
return this;
}
// define the getRecent function
ServerObject.prototype.getRecent = function(){
// do getRecent(); stuff
// reference object variables as this.variable;
}
// same for pollForNew();
ServerObject.prototype.pollForNew = function(){
// do pollForNew(); stuff here.
// reference object variables as this.variable;
}
Then in your program flow you do something like...
var server = new ServerObject("http://some.net/address");
server.variable = newValue; // access object variables
I mentioned the ADD in the first post. I'm smart enough to know how complex objects can be, and when I look for examples and explanations they expose certain layers of those complexities that cause my mind to just swim. It is difficult to drill down to the simple rules that get you started on the ground floor. What's the scope of 'this'? Sure I'll figure that out someday, but the simple truth is, you gotta reference 'this'.
Thanks
I wish I had more to offer.
Skip

call function inside a nested jquery plugin

There are many topics related to my question and i have been through most of them, but i haven't got it right. The closest post to my question is the following:
How to call functions that are nested inside a JQuery Plugin?
Below is the jquery plugin i am using. On resize, the element sizes are recalculated. I am now trying to call the function resizeBind() from outside of the jquery plugin and it gives me error
I tried the following combinations to call the function
$.fn.splitter().resizeBind()
$.fn.splitter.resizeBind()
Any ideas, where i am getting wrong?
;(function($){
$.fn.splitter = function(args){
//Other functions ......
$(window).bind("resize", function(){
resizeBind();
});
function resizeBind(){
var top = splitter.offset().top;
var wh = $(window).height();
var ww = $(window).width();
var sh = 0; // scrollbar height
if (ww <0 && !jQuery.browser.msie )
sh = 17;
var footer = parseInt($("#footer").css("height")) || 26;
splitter.css("height", wh-top-footer-sh+"px");
$("#tabsRight").css("height", splitter.height()-30+"px");
$(".contentTabs").css("height", splitter.height()-70+"px");
}
return this.each(function() {
});
};
})(jQuery);
I had the same problem. Those answers on related posts didn't work for my case either. I solved it in a round about way using events.
The example below demonstrates calling a function that multiplies three internal data values by a given multiplier, and returns the result. To call the function, you trigger an event. The handler in turn triggers another event that contains the result. You need to set up a listener for the result event.
Here's the plugin - mostly standard jQuery plugin architecture created by an online wizard:
(function($){
$.foo = function(el, options){
// To avoid scope issues, use 'base' instead of 'this'
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("foo", base);
base.init = function(){
base.options = $.extend({},$.foo.defaultOptions, options);
// create private data and copy in the options hash
base.private_obj = {};
base.private_obj.value1 = (base.options.opt1);
base.private_obj.value2 = (base.options.opt2);
base.private_obj.value3 = (base.options.opt3);
// make a little element to dump the results into
var ui_element = $('<p>').attr("id","my_paragraph").html(base.private_obj.value1 +" "+ base.private_obj.value2+" " +base.private_obj.value3);
base.$el.append(ui_element);
// this is the handler for the 'get_multiplied_data_please' event.
base.$el.bind('get_multiplied_data_please', function(e,mult) {
bar = {};
bar.v1 = base.private_obj.value1 *mult;
bar.v2 = base.private_obj.value2 *mult;
bar.v3 = base.private_obj.value3 *mult;
base.$el.trigger("here_is_the_multiplied_data", bar);
});
};
base.init();
}
$.foo.defaultOptions = {
opt1: 150,
opt2: 30,
opt3: 100
};
$.fn.foo = function(options){
return this.each(function(){
(new $.foo(this, options));
});
};
})(jQuery);
So, you can attach the object to an element as usual when the document is ready. And at the same time set up a handler for the result event.
$(document).ready(function(){
$('body').foo();
$('body').live('here_is_the_multiplied_data', function(e, data){
console.log("val1:" +data.v1);
console.log("val2:" +data.v2);
console.log("val3:" +data.v3);
$("#my_paragraph").html(data.v1 +" "+ data.v2+" " +data.v3);
});
})
All that's left is to trigger the event and pass it a multiplier value
You could type this into the console - or trigger it from a button that picks out the multiplier from another UI element
$('body').trigger('get_multiplied_data_please', 7);
Disclaimer ;) - I'm quite new to jQuery - sorry if this is using a hammer to crack a nut.
resizeBind function is defined as private so you cannot access it from outside of it's scope. If you want to use it in other scopes you need to define it like that
$.fn.resizeBind = function() { ... }
Then you would call it like that $(selector').resizeBind()
You have defined the resizeBind function in a scope that is different from the global scope. If you dont'use another javascript framework or anything else that uses the $ function (to prevent conflict) you can delete the
(function($){
...
})(jQuery);
statement and in this way the function will be callable everywhere without errors
I didn't test it:
this.resizeBind = function() { .... }

Categories

Resources