I'm using backbone.marionette for view control.
My issue is "How do you pass a parameter to a model?"
This is what I have tried:
define([
'jquery',
'underscore',
'backbone',
'models/CampaginModel',
'collections/CampaignCollection',
'text!templates/includes/_campaign.html'
], function ($, _, Backbone, CampaginModel, CampaignCollection, campaignTemplate) {
var campaginView = Backbone.Marionette.ItemView.extend({
template: campaignTemplate,
initialize: function (options) {
this.campaign_id = options.id;
},
model: CampaginModel({id: this.campaign_id}),
onRender: function () {
}
}); // end campagin view
return campaginView;
});
I have noticed that my parameter get passed to the view init function I'm kinda stuck after this point. In standard backbone I just created a new model in the render function and passed the parameter to the model that way. However Marionette views have a 'model' attribute which I think should allow me to pass in it there, but it does not!
Model:
define([
'underscore',
'backbone',
'jquery'
], function (_, Backbone, jquery) {
var CampaginModel = Backbone.Model.extend({
urlRoot: '/api/v1/campaign/',
// Model Constructor
initialize: function () {
},
});
return CampaginModel;
});
I don't know what your file structure looks like.
But it should be like something like this.
define([
'jquery',
'underscore',
'backbone',
'models/CampaginModel',
'collections/CampaignCollection',
'text!templates/includes/_campaign.html'
], function ($, _, Backbone, CampaginModel, CampaignCollection, campaignTemplate) {
var campaginView = Backbone.Marionette.ItemView.extend({
template: campaignTemplate,
initialize: function (options) {
this.campaign_id = options.id;
this.model.set({id: this.campaign_id});
},
model: CampaginModel,
onRender: function () {
}
}); // end campagin view
return campaginView;
});
I haven't test the code yet.
If you need to set your parameters to model, you have to use backbone's model.set() function
Related
I just started to lean Backbone, and underscore template, not sure if the structure suitable for it.
The question is, when I reload a template, how to re-bind event from Backbone which is re-run the events function.
The example is simply load an index page, insert main_option template into the page, and jump between main_option, and role_view template.
Here is the app.js which I put router in there:
define(['jquery', 'underscore', 'backbone', 'views/role_view', 'views/main_options'], function ($, _, Backbone, rolePage, mainOptions) {
var appRouter = Backbone.Router.extend({
$el: $('.container'),
initialize: function () {
this.mainOptionPage = mainOptions;
this.loginView = rolePage;
},
routes: {
"": "mainOption",
"views/role_view": "login"
},
mainOption: function () {
this.$el.html(this.mainOptionPage.render().$el);
},
login: function () {
this.$el.html(this.loginView.render().$el);
}
});
var router = new appRouter();
Backbone.history.start();
});
Here is the main_option.js
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
var Person = Backbone.Model.extend({
defaults: {
name: 'Guest Worker',
age: 23,
occupation: 'worker'
}
});
var testView = Backbone.View.extend({
$el: $('#indexPage'),
initialize: function () {
var self = this;
$.get('/test/templates/mainOptions.html').success(function (data) {
self.template_loaded(data);
template = _.template(data, {name: "Test"});
}, 'html');
},
events: {
'click .signButton': 'pageToSign'
},
pageToSign: function (e) {
e.preventDefault();
Backbone.history.navigate("views/role_view", {trigger: true});
},
template_loaded: function (html) {
var template = _.template(html, {name: "Test"});
this.$el.html(template);
return this;
}
});
var person = new Person;
return new testView({model: person});
});
and final page is role_view.js
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
var role = Backbone.View.extend({
initialize: function(){
var self = this;
$.get('/test/templates/chooseRole.html').success(function(html){
self.template_loaded(html);
});
},
events: {
'click .parentButton': 'parentClick'
},
template_loaded: function(html) {
var template = _.template(html, {name: "Test"});
this.$el.html(template);
return this;
},
parentClick: function(e) {
e.preventDefault();
Backbone.history.navigate("", {trigger: true});
}
});
return new role();
});
Thanks.
You real problem is that you're reusing views rather than destroying and creating them as needed. In your router, you have this:
mainOption: function () {
this.$el.html(this.mainOptionPage.render().$el);
},
login: function () {
this.$el.html(this.loginView.render().$el);
}
You call this.$el.html the first time, the view goes up, and everything seems to be okay. Then you switch views by calling this.$el.html and everything still seems to be okay. But the next time you switch views, your events are gone. This happens because of the way jQuery's html function works; from the fine manual:
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
Emphasis mine. Calling this.$el.html will destroy the event bindings on the previous content (such as this.mainOptionsPage.el or this.loginView.el).
If you create and destroy views as needed:
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
// Your Person model goes in its own file or possibly in the router file for now...
var TestView = Backbone.View.extend({
//...
});
return TestView; // Return the view "class", not an instance.
});
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
var Role = Backbone.View.extend({
//...
});
return Role;
});
define(['jquery', 'underscore', 'backbone', 'views/role_view', 'views/main_options', 'models/person'], function ($, _, Backbone, Role, TestView, Person) {
var person = new Person; // The person model is managed here.
var appRouter = Backbone.Router.extend({
//...
initialize: function () {
// Don't need anything in here anymore.
},
//...
mainOption: function () {
// Create a new view when we need it.
this.switchTo(new TestView({ model: person }));
},
login: function() {
// Create a new view when we need it.
this.switchTo(new Role);
},
switchTo: function(view) {
// Destroy the old view since we don't need it anymore.
if(this.currentView)
this.currentView.remove();
// Keep track of the new current view so that we can
// kill it alter and avoid leaks.
this.currentView = view;
this.$el.html(this.currentView.render().el);
}
});
//...
});
I'm having troubles handling events between my views and collections. In the below example you can find a short version of what does my webapp look like and how are the events being handled now.
What happens here is that when switching from menu1 to menu2 or even when going backwards, it causes that the "APP:change_city" event listener is stacked up. So when I then trigger this event , it calls the method OnCityChange() as many times as I switched between the menus.
I'm now not really sure whether I'm using the event aggregator (eMgr) correctly.
Can anyone please assist?
eMgr.js
define(['backbone.wreqr'],function(Wreqr){
"use strict";
return new Wreqr.EventAggregator();
})
AppRouter.js
define(['marionette'], function (Marionette) {
"use strict";
var AppRouter = Marionette.AppRouter.extend({
appRoutes: {
'menu1' : 'showMenu1',
'menu1' : 'showMenu2'
}
});
return AppRouter;
});
AppControler.js
define(['underscore', 'backbone', 'marionette', '../eMgr'], function (_, Backbone, Marionette, eMgr) {
"use strict";
var Controller = Marionette.Controller.extend({
initialize: function(){
console.log("AppRouter - Init")
},
showMenu1: function (city) {
console.log(" [Info] [AppControler] opening Menu1");
eMgr.trigger("APP:open_menu", { menu: "Menu1", city: city});
},
showMenu2: function (city) {
console.log(" [Info] [AppControler] opening Menu2");
eMgr.trigger("APP:open_menu", { menu: "Menu2", city: city});
}
});
return Controller;
});
App.js
define([ 'backbone', 'underscore', 'marionette', 'eMgr',
'layouts/MainMenu/layoutview.menu1',
'layouts/MainMenu/layoutview.menu2',
'controllers/AppController', 'routers/AppRouter'],
function (Backbone, _, Marionette, eMgr,
lv_mainmenu1, lv_mainmenu2,
AppController, AppRouter) {
"use strict";
var MyApp = new Marionette.Application();
var controller = new AppController();
MyApp.addRegions({
.....
mainmenu: '#main_menu',
.....
});
MyApp.listenTo(eMgr, "menu_changed",function(eData){
switch(eData.menu){
case "Menu1":
MyApp.mainmenu.show(new lv_mainmenu1(eData));
break;
case "Menu2":
MyApp.mainmenu.show(new lv_mainmenu2(eData));
break;
}
});
MyApp.addInitializer(function(options) {
var router = new AppRouter({
controller : controller
});
});
MyApp.on("start", function(){
if (Backbone.history){
Backbone.history.start();
}
});
$(document).ready(function() {
MyApp.start();
});
});
layoutview.menu1.js
define([ 'backbone', 'underscore', 'marionette',
'templates/template.mainmenu',
'layouts/MainMenu/collectionview.categories'],
function (Backbone, _, Marionette, t_Menus, c_Categories, cv_Categories) {
"use strict";
var Menu1LayoutView = Marionette.LayoutView.extend({
template: t_Menus['menu1'],
regions: {
menu : '#menu'
},
initialize: function(options){
this.city = options.city
},
onRender: function(){
},
onShow: function(){
this.menu.show(new cv_Categories({city:this.city}));
}
});
return Menu1LayoutView;
});
collectionview.categories.js
define([ 'backbone', 'underscore', 'marionette',
'layouts/MainMenu/compositeview.subcategories',
'collections/MainMenu/MM.collection.categories'],
function (Backbone, _, Marionette, cv_Subcategories, c_Categories) {
"use strict";
var CategoriesCollectionView = Marionette.CollectionView.extend({
initialize: function(options){
this.collection = new c_Categories([], {city: options.city});
},
getChildView: function(model){
return cv_Subcategories;
},
onRender: function(){
},
onShow: function(){
}
});
return CategoriesCollectionView;
});
This is where all the categorie's data are fetched from , it also re-fetches the data once the APP:change_city event is being triggered.
MM.collection.categories.js
define([ 'underscore', 'backbone', 'eMgr','models/MainMenu/MM.model.category'], function(_, Backbone, eMgr, m_Category){
var CategoriesCollection = Backbone.Collection.extend({
model: m_Category,
initialize: function(attr, opts) {
this.city = opts.city;
this.fetch();
eMgr.once("APP:change_city", this.OnCityChange, this)
},
url: function(){
return 'AF_GetCategories?city='+this.city;
},
OnCityChange: function(eData){
/// this is the part which is being called multiple times !!!!! ////
/// when checking eMgr's events , it shows that the events are stacking up ..
this.url= 'AF_GetCategories?city='+eData.city;
this.fetch();
}
});
return CategoriesCollection;
});
compositeview.subcategories.js
define([ 'backbone', 'underscore', 'marionette',
'templates/template.mainmenu',
'layouts/MainMenu/itemview.subcategory'],
function (Backbone, _, Marionette, t_MainMenu, iv_Subcategory) {
"use strict";
var SubcategoriesCompositeView = Marionette.CompositeView.extend({
template: t_Menus['subcategorieslayout'],
childViewContainer: "#category-wrapper",
getChildView: function(model){
return iv_Subcategory;
},
initialize: function(){
this.collection = this.model.get("subcategories");
},
onRender: function(){
},
onShow: function(){
this.$el.find("#loading").fadeOut(150);
}
});
return SubcategoriesCompositeView;
});
I have come to a conclusion that keeping the event listeners this.listenTo("custom_event", this.do_something) in either model or collection isn't a good idea. The events weren't cleaned up properly while switching between menu1 and menu2. It only worked when I manually called eMgr.stopListening() before loading any views.
So I tried moving all the event listeners from models/collections to their views and Voila!...it all worked! Events are no longer being triggered multiple times as before.
I'm using require.js with backbone. My question: is how do I fetch.() my model from within my view. What I have tried is below, however I get the error 'Campaign is undefined'. I think I'm very close:
Model:
define([
'underscore',
'backbone'
], function(_, Backbone) {
var Campagin = Backbone.Model.extend({
urlRoot: '/api/v1/campaign/'
});
return Campagin;
});
View:
define([
'jquery',
'underscore',
'backbone',
'views/RewardView',
'views/FriendRewardView',
'models/CampaginModel',
'text!templates/backbone/portal/campaignTemplate.html'
], function($, _, Backbone, campaignTemplate){
var CampaginView = Backbone.View.extend({
el: '#campaign-panel',
render: function(options) {
if(options.id){
var campaign = new Campagin({id: options.id});
campaign.fetch({
success: function(campaign){
// We can only get the reward when the campaign reward url is returned.
var rewardview = new RewardView();
rewardview.render({reward_url: campaign.get('participant_reward')});
var friendview = new FriendRewardView();
friendview.render({reward_url: campaign.get('friend_reward')});
var template = _.template(campaignTemplate, {campaign: campaign});
this.$el.html(template);
}// end success
}); // end fetch
}// end if option.id
} // end render function
}); // end campagin view
return CampaginView;
});
In your View you are specifying an array of dependencies, which will be passed to the definition function as function arguments, listed in the same order as the order in the array. But you only declared 4 arguments: $ (jQuery), _ (underscore), Backbone and campaignTemplate(which is wrong because according your dependencies should be RewardView). So you have to declare properly your functions. For example:
define([
'jquery',
'underscore',
'backbone',
'views/RewardView',
'views/FriendRewardView',
'models/CampaginModel',
'text!templates/backbone/portal/campaignTemplate.html'
], function($, _, Backbone, RewardView, FriendRewardView, Campagin, campaignTemplate){
...
}
Check the documentation of Require JS for more info.
I'm picking up backbone for the first time and I'm having some trouble getting my view to render my collection.
main.js
/*global require*/
'use strict';
require.config({
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
},
paths: {
app: 'app',
jquery: '../components/jquery/jquery',
backbone: '../components/backbone-amd/backbone',
underscore: '../components/underscore-amd/underscore',
competitions: 'collections/competition-collection',
competitionModel: 'models/Competition-model',
templates: 'templates'
}
});
require([
'backbone',
'app',
'competitions',
'competitionModel',
'views/competition-view',
'templates'
], function (
Backbone,
App,
Competitions,
CompetitionModel,
CompetitionsView
) {
window._app = new App(
Competitions,
CompetitionModel,
CompetitionsView
);
window._app.demoData();
window._app.start();
});
app.js
define([], function() {
var App = function(Competitions,CompetitionModel,CompetitionsView) {
// Our models will be instantiated later as needed later.
this.Models.CompetitionModel = CompetitionModel;
this.Collections.Competitions = Competitions;
this.Collections.competitions = new Competitions();
this.Views.competitionsView = new CompetitionsView();
//console.log(this.Views.competitionsView)
};
App.prototype = {
Views: {},
Models: {},
Collections: {},
start: function() {
this.Views.competitionsView.render();
Backbone.history.start();
},
// TODO: We'll get rid of this or move later ... just "spiking" ;)
demoData: function() {
var me = new this.Collections.Competitions(
[
{
name: 'Some Name',
},
{
name: 'Other Name',
}
]
);
console.log("***** Demo Competitions Created *****");
}
};
return App;
});
Competition-model.js
define([
'underscore',
'backbone',
], function (_, Backbone) {
'use strict';
var CompetitionModel = Backbone.Model.extend({
defaults: {
},
initialize: function(){
console.log(this.attributes);
}
});
this.listenTo(Competitions, 'add', function(){
console.log("bla")
});
return CompetitionModel;
});
competition-collection.js
define([
'underscore',
'backbone',
'models/competition-model'
], function (_, Backbone, CompetitionModel) {
'use strict';
var CompetitionCollection = Backbone.Collection.extend({
model: CompetitionModel
});
return CompetitionCollection;
});
competition-view.js
define([
'jquery',
'underscore',
'backbone',
'templates',
'competitions',
], function ($, _, Backbone, JST, Competitions) {
'use strict';
var CompetitionView = Backbone.View.extend({
template: JST['app/scripts/templates/competition.ejs'],
render: function() {
console.log(this.model);
}
});
console.log("yo")
return CompetitionView;
});
I know that the models are loaded correctly but I can't seem to figure out how to pass the model collection to the view and render all the objects.
Can anyone help?
Thanks
You have created the view, collection and models properly but haven't created a link between collection and view. You need to pass the collection to the view and use that collection in the view to render all models.
In your app.js replace:
this.Views.competitionsView = new CompetitionsView();
With:
this.Views.competitionsView = new CompetitionsView({collection: this.Collections.competitions});
Now you have a reference of collections object in your view. Now inside competition-view.js replace:
console.log(this.model);
With:
this.collection.each(function (model) {
console.log(model);
});
Also in your app.js, inside start function, you are calling Backbone.history.start() without creating a Backbone router, which is also giving a console error.
I'm using Require.js with Backbone.js and Underscore.js, and I have a nested view that is coming up as undefined when called as a dependency, but when I have the two views in the same module, they work fine. I'm wondering what I'm doing wrong. Here's an example:
child-view.js
define([
'jQuery',
'Underscore',
'Backbone',
], function ($, _, Backbone) {
var ChildView = Backbone.View.extend({
initialize: function () {
_.bindAll(this, 'render');
this.render();
},
});
return ChildView;
});
parentview.js
define([
'jQuery',
'Underscore',
'Backbone',
'src/views/child-view'
], function ($, _, Backbone, ChildView){
var ParentView = Backbone.View.extend({
initialize: function () {
_.bindAll(this, 'render');
this.render();
},
render: function () {
child = new ChildView({});
}
});
return ParentView;
});
I receive a "Uncaught TypeError: undefined is not a function" when trying to call the new ChildView. If I reference the ChildView outside of the Parentview but inside of parentview.js, it displays the view, but as an object.
Just from your code, there should be no problem, I tested your code actually did not find the problem.
This is my test code,you can try it:
http://files.cnblogs.com/justinw/test_byfejustin.zip
I think it might be your “require.js” have a problem,you can replace your "require.js" with my "test_byfejustin\js\libs\require\require.js" in my code package,and try again.
Variable names are case-sensitive. In child-view.js you are returning "ChildView" which is undefined (you've assigned childView).