I'm working on a Backbone.js app which utilizes a 'master view' which all views and subviews extend from.
Master view
define(['backbone'], function (Backbone) {
return Backbone.View.extend({
events: {
},
showSuccess: function (msg) {
alert(msg);
}
});
});
I then have a Main View which generates the page, this can call on sub views for smaller parts:
define(['backbone','masterView', 'mySubView'], function (Backbone, mView, mySubView) {
var mainView = mView.extend({
events: function () {
return _.extend({}, coreView.prototype.events, {
});
},
render: function () {
var sub = new mySubView({'foo': 'bar'});
}
});
return new mainView();
});
Finally, my subview, which when it's initialised, it says that options is undefined.
define(['backbone','masterView', 'mySubView'], function (Backbone, mView, mySubView) {
var subView = mView.extend({
events: function () {
return _.extend({}, coreView.prototype.events, {
});
},
initialize: function (options) {
console.log(options);
}
});
return new subView();
});
In this setup, why is options undefined when I passed them in my MainView? If the subview doesn't extend masterView, but Backbone.view instead, it works fine.
Your last line in the subview file:
return new subView();
You're returning a new instance instead of returning the constructor in the subview module. It should be:
return subView;
Note that as a convention, JavaScript code should use PascalCase for types (constructor, classes, etc.), and instances (variables, properties, etc.) should use camelCase.
Also, I'm sharing tricks on how to design a good base class with Backbone. You could shift the responsibility of merging the events to the base class instead of each child class.
Related
I have a div element in my shell.html that uses the compose binding to load a view and view model:
<div data-bind="compose: { model: 'viewmodels/subMenu' }"></div>
My shell.js looks like:
import common = require("helpers/common");
class Shell {
view: any; router: DurandalRootRouter;
activate: () => Q.Promise<any>;
constructor() {
var self = this;
self.view = common.view;
self.router = common.router;
common.router.map([ { route: '', title: 'Home', moduleId: 'viewmodels/Home', nav: true } ]);
self.activate = () => { return Q.when(common.router.activate()); }
}
}
export = Shell
My subMenu.js view model looks like the following:
define([], function () {
"use strict";
return {
isPreview: ko.observable(false)
};
});
I then have another view model which imports this subMenu viewmodel with requirejs and changes the 'isPreview' property value. But when it imports the submenu view model, it creates a new instance rather than accessing the existing one. Based on the durandal docs: http://durandaljs.com/documentation/Creating-A-Module.html
In the above example, both modules returned an object instance. This results in what would commonly be called a "singleton" object, since the same object instance is obtained by all who require it.
I understand that because it returns an object this should therefore be the same instance instead of being transient?
I am using Backbone and Layout Manager. I have this code inside MyView.js:
afterRender: function() {
var scope = this;
this.model.get("books").each(function(bookModel) {
var bookView = new BookView({
model: bookModel
});
scope.insertView(".books", bookView).render();
});
},
Inside BookView.js I have afterRender method:
afterRender: function() {
console.log("after render");
},
I have 6 items in the books property of the model and I call render() for each book. Eventually what I get is "after render" logged only once. What is wrong? Where are the missing 5 "after render" logs??
The code above was invoking inside MyView's afterRender method. For unknown reasons many calls to render() one by one don't invoke each book's afterRender().
After reading again and again in the LayoutManager documentation I realized that I need to call insertView() inside the beforeRender() method without rendering the views. This way render() will render all the sub-views and afterRender() will invoked properly:
beforeRender: function() {
var scope = this;
this.model.get("books").each(function(bookModel) {
var bookView = new BookView({
model: bookModel
});
scope.insertView(".books", bookView);
});
},
I am new in SPA's with backbone and I am trying to develop a small app by using backbone and requireJs.
The problem I faced is that I can't extend a view by passing a collection.
Well, this is the view with name MenuView.js
define([
'Backbone'
], function (Backbone) {
var MenuView = Backbone.View.extend({
tagName: 'ul',
render: function () {
_(this.collection).each(function (item) {
this.$el.append(new MenuListView({ model: item }).render().el);
}, this);
return this;
}
});
return new MenuView;
});
and this is the router.js in which the error is appeared
define([
'Underscore',
'Backbone',
'views/menu/menuView',
'views/createNew/createNew',
'collections/menu/menuCollection',
], function (_, Backbone, MenuView, CreateNewView,Menucollection) {
var AppRouter = Backbone.Router.extend({
routes: {
'index': 'index',
'action/:Create': 'Create'
},
index: function () {
CreateNewView.clear();
//----------- HERE IS THE PROBLEM ------------
$('#menu').html(MenuView({ collection: Menucollection.models }).render().el);
},
Create: function () {
CreateNewView.render();
}
});
var initialize = function () {
var appRouter = new AppRouter();
Backbone.history.start();
appRouter.navigate('index', { trigger: true });
};
return {
initialize: initialize
};
});
The error message is "object is not a function". I agreed with this since the MenuView is not a function. I tried to extend the MenuView (MenuView.extend({collection:Menucollection.models})) and the error message was "objet[object,object] has no method extend".
I suppose that the way I am trying to do this, is far away from the correct one.
Could anyone suggest how to do this?
Thanks
#Matti John's solution will work, but it's more of a workaround than a best practice IMHO.
As it is, you initializing your view just by requiring it, which:
Limits you to never accept arguments
Hits performance
Makes it really hard to unit-test if you relay on assigning properties ater constructing an instance.
A module should be returning a 'class' view and not an instance on that view.
In MenuView.js I would replace return new MenuView with return MenuView; and intitalzie it when required in router.js.
Your MenuView.js returns an initialized MenuView, so you could just do:
MenuView.collection = Menucollection
Note I haven't selected the models - I think it's better if you don't use the models as a replacement for your view's collection, since it would be confusing to read the code and not have a Backbone collection as the view's collection. You would also lose the method's contained within the collection (e.g. fetch/update).
If you do this, then you would need to update your loop (each is available as a method for the collection):
this.collection.each(function (item) {
this.$el.append(new MenuListView({ model: item }).render().el);
}, this);
I would like to access the app.vent from Marionette.ItemView.
Maybe an option could be to pass a parameter (app.vent) to Marionette.ItemView from Marionette.CompositeView.
Here my code:
// view/compositeView.js
define([
'marionette',
'views/item'
], function (Marionette, itemView) {
var ListView = Marionette.CompositeView.extend({
itemView: itemView
});
});
Any ideas?
P.S.:
I cannot access the app from itemView because there is a problem of circular dependency.
app -> view/compositeView -> view/itemView
v0.9 added an itemOptions attribute that can be used for this. It can either be an object literal or a function that returns an object literal.
Backbone.Marionette.CompositeView.extend({
itemView: MyItemViewType,
itemViewOptions: {
some: "option",
goes: "here"
}
});
All of the key: "value" pairs that are returned by this attribute will be supplied to the itemview's options in teh initializer
Backbone.Marionette.ItemView.extend({
initialize: function(options){
options.some; //=> "option"
options.goes; //=> "here"
}
});
Additionally, if you need to run specific code for each itemView instance that is built, you can override the buildItemView method to provide custom creation of the item view for each object in the collection.
buildItemView: function(item, ItemView){
// do custom stuff here
var view = new ItemView({
model: item,
// add your own options here
});
// more custom code working off the view instance
return view;
},
For more information, see:
the change log for v0.9
the CollectionView documentation for itemViewOptions - note that CompositeView extends from CollectionView, so all CollectionView docs are valid for CompositeView as well
the buildItemView annotated source code
Since Marionette v2.0.0, childViewOptions is used instead of itemViewOptions to pass parameters to the child view:
var MyCompositeView = Marionette.CompositeView.extend({
childView: MyChildView,
childViewOptions: function(model, index) {
return {
vent: this.options.vent
}
}
});
var MyChildView = Marionette.ItemView.extend({
initialize: function(options) {
// var events = options.vent;
}
});
new MyCompositeView({ vent: app.vent, collection: myCollection});
But to work with events, lets use Marionette.Radio instead of passing app.vent to the view.
I am trying to implement a simple app which is able to get a collection for a given object_id.
The GET response from the server looks like this:
[
{object_id: 1, text: "msg1"},
{object_id: 1, text: "msg2"},
{object_id: 1, text: "msg3"},
.......
]
My goal is:
render a collection when the user choose an object_id.
The starting point of my code is the following:
this.options = {object_id: 1};
myView = new NeView(_.extend( {el:this.$("#myView")} , this.options));
My question is:
* What is the best way:
1) to set the object_id value in the MyModel in order to
2) trigger the fetch in MyCollection and then
3) trigger the render function in myView?* or to active my goal?
P.S:
My basic code looks like this:
// My View
define([
"js/collections/myCollection",
"js/models/myFeed"
], function (myCollection, MyModel) {
var MyView = Backbone.View.extend({
initialize: function () {
var myModel = new MyModel();
_.bindAll(this, "render");
myModel.set({
object_id: this.options.object_id
}); // here I get an error: Uncaught TypeError: Object function (){a.apply(this,arguments)} has no method 'set'
}
});
return MyView;
});
// MyCollection
define([
"js/models/myModel"
], function (MyModel) {
var MyCollection = Backbone.Collection.extend({
url: function () {
return "http://localhost/movies/" + myModel.get("object_id");
}
});
return new MyCollection
});
//MyModel
define([
], function () {
var MyModel = Backbone.Model.extend({
});
return MyModel
});
There's a few, if not fundamentally things wrong with your basic understanding of Backbone's internals.
First off, define your default model idAttribute, this is what identifies your key you lookup a model with in a collection
//MyModel
define([
], function () {
var MyModel = Backbone.MyModel.extend({
idAttribute: 'object_id'
});
return MyModel
});
in your collection, there is no need to define your URL in the way you defined it, there are two things you need to change, first is to define the default model for your collection and second is to just stick with the base url for your collection
// MyCollection
define([
"js/models/myModel"
], function (MyModel) {
var MyCollection = Backbone.MyCollection.extend({
model: MyModel, // add this
url: function () {
return "http://localhost/movies
}
});
return MyCollection // don't create a new collection, just return the object
});
and then your view could be something along these lines, but is certainly not limited to this way of implementing
// My View
define([
"js/collections/myCollection",
"js/models/myFeed"
], function (MyCollection, MyModel) {
var MyView = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection = new MyCollection();
this.collection.on('add', this.onAddOne, this);
this.collection.on('reset', this.onAddAll, this);
},
onAddAll: function (collection, options)
{
collection.each(function (model, index) {
that.onAddOne(model, collection);
});
},
onAddOne: function (model, collection, options)
{
// render out an individual model here, either using another Backbone view or plain text
this.$el.append('<li>' + model.get('text') + '</li>');
}
});
return MyView;
});
Take it easy and go step by step
I would strongly recommend taking a closer look at the exhaustive list of tutorials on the Backbone.js github wiki: https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites ... try to understand the basics of Backbone before adding the additional complexity of require.js