On my page, I will have a slider which will have html inside, that will be populated using data fetched from the server.
I would like for the slider to be built and populated using jQuery, leaving Backbone to handle the viewing and events.
For this, I would need the data from the Backbone model, which leads to my question:
Is it fine to pass the model into jQuery OR would it be better to leave everything to the jQuery function and do a $.ajax fetch in the function instead.
Backbone
define(['backbone', 'models/model','slider'], function(Backbone, Model, Slider) {
var View = Backbone.View.extend({
render: function() {
$('#slider').Slider( this.model );
var template = _.template();
this.$el.html(template);
return this;
}
});
return View;
});
jQuery
(function($, window, document, undefined) {
"use strict";
$.fn.Slider = function(model) {
// do stuff with model
}
})(jQuery, window, document);
I'd implement the event handling and logic directly in the backbone view, where you already have the model and all other backbone objects you might possibly want to use. If you need the model data in the slider initialization you should not pass the model itself, but the json representation of the model data using
$('#slider').Slider( this.model.toJSON() );
Related
Good morning guys. I have a little understanding problem with backbone.js. i have a javascript sdk from a backend as a service with some getter and setter methods to get datas from this platform.
I have load this javascript sdk with require.js an it´s work fine. Now i need to create some models that work with this getter and setter methods to get this data to my collection an finally to my view. I do not have any clue...maybe someone have the right idea for me.
This is my current model:
define(['jquery','underscore','backbone'], function($,_,Backbone) {
var holidayPerson = Backbone.Model.extend({
initialize: function() {
console.log("init model holidayPerson");
this.on("change", function(data) {
console.log("change model holidayPerson"+JSON.stringify(data));
});
}
});
return holidayPerson;
});
Actually i create an instance of my model in my view:
define(['jquery','underscore','backbone','text!tpl/dashboard.html','holidayPerson','apio'], function($,_,Backbone,tpl, holidayperson, apio) {
template = _.template(tpl);
var usermodel = new holidayperson();
var dashboardView = Backbone.View.extend({
id: 'givenname',
initialize: function() {
console.log("dashboard view load");
usermodel.on('change', this.render);
var user = new apio.User();
user.setUserName('xxx');
user.setPassword('xxx');
apio.Datastore.configureWithCredentials(user);
apio.employee.getemployees("firstName like \"jon\" and lastName like \"doe\"", {
onOk: function (objects) {
console.log("apio: " + JSON.stringify(objects));
usermodel.set({mail: objects[0]['data']['mail'],lastname: objects[0]['data']['lastName'], username: objects[0]['data']['userName'], superior: objects[0]['data']['superior']});
}
});
},
render: function() {
console.log("render dashboard view");
console.log(usermodel.get('mail'));
console.log(usermodel.get('lastname'));
this.$el.html(template());
return this;
}
});
return dashboardView;
});
I think this not the right way...can i override the getter and setter method from this model ? Or maybe the url function ? Anyone now what is the best practice ?
Thanks a lot :-)
First of all, make sure that your render operation is asynchronous, as your API call will be and the usermodel params won't be set until that operation completes. If you render method fires before that, it will render the empty usermodel, since the data will not be there yet.
Second, a model need not fetch its own data, in my opinion. If you are going to have multiple users, you could use a collection to hold those users and then override the collection's sync method to handle the fetching of data from the API, but if there's no collection, it seems logical to me to have a method that does the data fetching and setting thereafter, as you've done.
I have backbonejs form inside the lightbox with html <select> as child view.
For the select <option> data I am loading from server and I have separate model and collection for this select
<select name="organization" id="organization" class="main__form--select main__form--select--js">
<option value="no">Organizations not found, Please add one</option>
</select>
Model for option (optionModel)
return Backbone.Model.extend({
defaults : {
"name" : 'KFC',
"email" : 'info#kfc.com',
"image" : '/kfc.jpg',
"descrption" : 'Lorem Ipsum'
}
});
This is view for the model
return Backbone.View.extend({
model : optionModel,
template : _.template(template),
render : function () {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
This is options collection
return Backbone.Collection.extend({
model : optionModel,
getQuery : function(){
//all my query codes
}
});
Options collections view render() code
this.collection.each(function (optionModel) {
// inserting each options view to an array
_this._optionsViewArray.push(
new OptionView({
model: optionModel
}).render().el
);
});
//inserting array to collection view container
_this.$el.html(_this._optionsViewArray);
return this;
My Parent view (form view) i create after render function with underscore _.wrap and inside that function
//<select>
var _selector = this.$el.find('#organization');
optionsView = new OptionsCollectionView({
collection : optionsCollection,
$el: _selector
});
optionsCollection.getQuery();
optionsView.render();
But Form is loading perfectly and Options collection querying successfully but nothing changes on <select> html, It's not updating.
Assuming that getQuery() does an asynchronous query (either using jQuery or Collection.fetch()), the problem (or at least one problem) is that you're calling optionsView.render() to soon, before the query results have returned.
You could throw in an arbitrary 5 second timeout to verify that this is the problem like this: setTimeout(function() { optionsView.render(); }, 5 * 1000);, but the correct way to do it is to call render from a jQuery done handler function ($.ajax({done: function() { ... }})) or (better) a Backbone sync event handler (this will only get called if you did the query via a Backbone collection fetch()): optionsCollection.on('sync', function() { ... });
You example is incomplete. However, given that fetches are generally asynchronous in Backbone and jQuery, this is the most obvious issue is that optionsView.render will run before optionsCollection has had a chance to fully load the collection. You can remedy this by listening to the collection update event:
optionsView = new OptionsCollectionView({
collection : optionsCollection,
$el: _selector
});
optionsView.listenTo(optionsCollection, 'update', optionsView.render);
optionsCollection.getQuery();
You could listen to the sync event instead, but listening to update means that local changes to the collection will also trigger updating your view.
There is also an issue with your render function, as you are passing an array of html elements into the jQuery html function.
render: function() {
var $el = this.$el;
$el.empty();
this.collection.each(function (optionModel) {
var view = new OptionView({ model: optionModel });
$el.append(view.render().$el);
});
return this;
}
However you may be better off using a standard collection view pattern, or something like Backbone.CollectionView - http://rotundasoftware.github.io/backbone.collectionView/
I can create a simple model like so:
define(["models/base/model"], function(Model) {
"use strict";
var IssueModel = Model.extend({
defaults:{
lastName: "Bob",
firstName: "Doe"
}
});
return IssueModel;
});
And then from my controller I can do this:
this.model = new IssueModel();
And then when I create my view I can pass it my model like so:
this.view = new IssueView({model: this.model});
Finally, in my template I can successfully get properties on the model by doing this:
Hi {{firstName}} {{lastName}}
But when I define a collection using IssueModel and I try to pass the collection to my view (and not the model like I showed previously) I can't figure out how to reference the models in my Handlebars template:
var self = this;
this.collection = new IssueCollection();
this.collection.fetch({
success: function(collection) {
self.view = new IssueView({collection: collection});
console.log(self.collection);
},
error: function(collection, error) {
// The collection could not be retrieved.
}
});
I know fetch properly retrieves 5 models from my Parse.com backend because this is what I get on the console:
My question is this. I know Chaplin.js uses getTemplateData, but when I pass a model I don't have to do anything special in order to reference the properties in my view. How would I reference, specifically iterate, over the collection I passed to my view in my Handlebars template?
{{#each [Model in the collection I passed to the view]}}
{{title}}
{{/each}}
Chaplin will render a collection using a CollectionView, it's basicly an extention of a normal view that listens for changes in your collection and adds/removes subviews accordingly.
this.view = new IssueCollectionView({collection: this.collection});
Also there is no need to wait for success call when using a collection view since it will automaticly render every child item when data is added.
I have the following problem with backbone and I'd like to know what strategy is the more appropriated
I have a select control, implemented as a Backbone view, that initially loads with a single option saying "loading options". So I load an array with only one element and I render the view.
The options will be loaded from a collection, so I fire a fetch collection.
Then I initialize a component that is in charge of displaying in line errors for every field. So I save a reference of the dom element of the combo.
When the fetch operation is finally ready, I rerender the control with all the options loaded from the collection.
To render the view I user something like this:
render: function() {
this.$el.html(this.template(this.model.attributes));
return this;
}
pretty standard backbone stuff
the problem is that after rendering the view for the second time the reference of the dom is no longer valid,
perhaps this case is a bit strange, but I can think of lots of cases in which I have to re-render a view without losing their doms references (a combo that depends on another combo, for example)
So I wonder what is the best approach to re-render a view without losing all the references to the dom elements inside the view...
The purpose of Backbone.View is to encapsulate the access to a certain DOM subtree to a single, well-defined class. It's a poor Backbone practice to pass around references to DOM elements, those should be considered internal implementation details of the view.
Instead you should have your views communicate directly, or indirectly via a mediator.
Direct communication might look something like:
var ViewA = Backbone.View.extend({
getSelectedValue: function() {
return this.$(".combo").val()
}
});
var ViewB = Backbone.View.extend({
initialize: function(options) {
this.viewA = options.viewA;
},
doSomething: function() {
var val = this.viewA.getSelectedValue();
}
});
var a = new ViewA();
var b = new ViewB({viewA:a});
And indirect, using the root Backbone object as a mediator:
var ViewA = Backbone.View.extend({
events: {
"change .combo" : "selectedValueChanged"
},
selectedValueChanged: function() {
//publish
Backbone.trigger('ViewA:changed', this.$('.combo').val());
}
});
var ViewB = Backbone.View.extend({
initialize: function(options) {
//subscribe
this.listenTo(Backbone, 'ViewA:changed', this.doSomething);
},
doSomething: function(val) {
//handle
}
});
var a = new ViewA();
var b = new ViewB();
The above is very generic, of course, but the point I'm trying to illustrate here is that you shouldn't have to worry whether the DOM elements are swapped, because no other view should be aware of the element's existence. If you define interfaces between views (either via method calls or mediated message passing), your application will be more maintainable and less brittle.
I am trying to use iScroll4 inside a backbone.js application. I have several dynamically loaded lists, and I want to initialize iScroll after the appropriate view has loaded.
I'm trying to call 'new iScroll' when the list view finishes loading, but cannot for the life of me figure out how to do this.
Has anyone gotten these two to work together? Is there an example out there of a backbone view initializing a scroller once its element has loaded?
you are correct, you have to load the view first,
or defenately refresh iscroll afterwards
in our applications, we usually use the render method to render the view
and have a postRender method that handles initialization of these extra plugins like iscroll
of course you need some manual work to get it done but this is the gist of it:
var myView = Backbone.View.extend({
// more functions go here, like initialize and stuff... but I left them out because only render & postRender are important for this topic
// lets say we have a render method like this:
render: function() {
var data = this.collection.toJSON();
this.$el.html(Handlebars.templates['spotlightCarousel.tmpl'](data));
return this;
},
// we added the postRender ourself:
postRender: function() {
var noOfSlides = this.collection.size();
$('#carouselscroller').width(noOfSlides * 320);
this.scroller = new IScroll('carouselwrapper', {
snap: true,
momentum: false,
hScrollbar: false
});
}
});
now the calling of these methods
we did this outside our view as we like some view manager to handle this
but it boils down to this
var col = new myCollection();
var view = new myView({ collection: col });
$('#wrapper').html(view.render().$el); // this chaining is only possible due to the render function returning the whole view again.
// here we always test if the view has a postRender function... if so, we call it
if (view.postRender) {
view.postRender();
}