I am trying to create and initialize some sort of master view model that contains common view models that might be run on every page and page specific models that are appended on page load.
var MasterViewModel = {
commonViewModel1 : CommonViewModel1(),
commonViewModel2 : CommonViewModel1()
};
var commonInit = function() {
// Populate View Model Data
MasterViewModel.commonViewModel1 = initCommonViewModel1();
MasterViewModel.commonViewModel2 = initCommonViewModel2();
// Apply common view model bindings
ko.applyBindings(MasterViewModel);
};
var pageSpecificInit = function() {
// Populate Specific View Model Data
MasterViewModel.pageViewModel1 = initPageViewModel1();
MasterViewModel.pageViewModel2 = initPageViewModel2();
// Apply Page Specific Bindings
ko.applyBindings(MasterViewModel);
};
$(function() {
commonInit();
pageSpecificInit();
});
this is a crude example of what I am trying to do in the real application this is all namespaced and in separate files so that only page specific code is run. What is the best practice for doing this I somewhat based the above on http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html but when I do it in the application I get something like "cannot bind to pageViewModel1 undefined" should I setup my MasterViewModel differently to be more like
var MasterViewModel = {
commonViewModel1 : CommonViewModel1(),
commonViewModel2 : CommonViewModel1(),
pageViewModels : {}
};
var commonInit = function() {
// Populate View Model Data
MasterViewModel.commonViewModel1 = initCommonViewModel1();
MasterViewModel.commonViewModel2 = initCommonViewModel2();
// Apply common view model bindings
ko.applyBindings(MasterViewModel);
};
var pageSpecificInit = function() {
// Populate Specific View Model Data
MasterViewModel.pageViewModels.pageViewModel1 = initPageViewModel1();
MasterViewModel.pageViewModels.pageViewModel2 = initPageViewModel2();
// Apply Page Specific Bindings
ko.applyBindings(MasterViewModel.pageViewModels);
};
$(function() {
commonInit();
pageSpecificInit();
});
Your second example is more correct, but shouldn't you be binding the page-specific view models to a specific html element that you've surrounded with the stop binding comment?
ko.applyBindings(MasterViewModel.pageViewModels, $('#pageElement')[0]);
However, if you want to have nicely decoupled objects that can talk to each other, then you might want to look at Knockout Postbox
Related
Is there a more elegant way than the one below to append another view to a region? I'd like to append as many chat windows when a button is clicked, and destroy it when a button within the chat window is clicked.
The one below requires to keep track of an index per element:
var AppLayoutView = Backbone.Marionette.LayoutView.extend({
template: "#layout-view-template",
regions: {
wrapperChat : '#wrapper-chat'
}
appendView: function ( incremennt, newView ){
this.$el.append( '<div id="view'+increment+'" >' ) ;
this.regionManager.addRegion( 'view'+increment , '#view'+increment )
this['view'+increment].show ( newView ) ;
}
});
// ChatView
var ChatView = Marionette.ItemView.extend({
template: "#chat-template"
});
// Layout
var LayoutView = new AppLayoutView();
LayoutView.render();
// Append View
LayoutView.wrapper.appendView(++index, new ChatView());
Regions are designed to show a single View. Marionette's abstraction for repeating views is CollectionView, which renders an ItemView for each Model in a Collection.
You add or remove Models from the Collection; Marionette handles the view updates for you.
If your ChatView already has a model, use that. If not, you could add a trivial model to abstract away the index variable.
// Collection for the Chat models.
// If you already have Chat Collection/Models, use that.
// If not, create a simple Collection and Models to hold view state, e.g.:
var chats = new Backbone.Collection();
// CollectionView "subclass"
var ChatCollectionView = Marionette.CollectionView.extend({
itemView: ChatView
})
// Add a single ChatCollectionView to your region
var chatsView = new ChatCollectionView({ collection: chats });
LayoutView.getRegion('wrapperChat').show();
// To add a ChatView, add a Model to the Collection
var nextChatId = 0;
chart.addChat(new Backbone.Model({ id: nextChatId++ }));
// To remove a chat, remove its model
chart.remove(0);
I am trying to implement a list-details view. The list is generated with $firebaseArray(ref). When an item on the list is clicked, the list controller uses list.$getRecord(item.$id) to get the particular record. Puts it in a global service(just and empty object with set and get) and in my detail controller i assign that service(already set to the selected item) to a scope variable in the detail controller and display it.
The information in the detail view is editable. and when it is editted, a save button appears which when clicked saves the edit using this code
item = editItem; //editItem contains the new changes made on the detail page
list.$save(item).then(function(ref){
//ref.key() === item.$id; //
console.log("Your Edit has been saved');
});
This works. The edits are reflected on the remote firebase data.
But the problem occurs when i navigate back to the list view and try to click another item. It gets an error which says list.$getRecord() is not a function. Now this error doesn't occur when you don't save an edit on the details view.
I printed out the list array before and after i save and i realised this
List array before an item is saved (contains AngularFire methods)
List array after an item is saved (no longer contains AngularFire methods)
I have no idea why $firebaseArray is reacting this way. Is there something i am missing? is this a normal behaviour?
PS: i am using ionic and angularFire.
I can post more code if neccesary
EDIT
Here is an abstraction of the code
List.html
<ion-list>
<ion-item href="#/lead/info" ng-click="vm.selectItem(l.$id)" ng-repeat="l in vm.list" >
<h3>{{l.firstName}} {{l.lastName}}</h3>
<h4 class="">
<p>{{l.topic}}</p>
</h4>
</ion-item>
</ion-list>
list.js (controller function)
function ListCtrl(selectedItem, $firebaseArray) {
/* jshint validthis: true */
var vm = this;
vm.list= {};
vm.selectItem = selectItem;
loadList(); //Loads the List array
function loadList() {
var fireList = new Firebase("https://xxxxx.firebaseio.com/list");
var r = $firebaseArray(fireList);
r.$loaded(function () {
vm.list = r;
});
console.log(vm.list); //Outputs the first image(above). But after an item edit and i go back, outputs the second image(above)
}
function selectItem(index) {
var sItem = vm.list.$getRecord(index);
selectedItem.setList(vm.list);
selectedItem.setItem(sItem);
}
}
The selectedItem service is simple. i use it to set a single object or array of objects
function selectedItem() {
var sItem = {};
var List = {};
return {
getItem: function () {
return sItem;
},
setItem: function (authObject) {
sItem = authObject;
},
getList: function(){
return List;
},
setList: function(al){
List = al;
}
};
};
The detail view controller is ass so:
item.js(controller function)
function ItemCtrl(selectedItem, $scope, $firebaseObject) {
/* jshint validthis: true */
var vm = this;
$scope.selectedItem = selectedItem.getItem();
$scope.listArray = selectedItem.getList();
//vm.item = $scope.selectedItem;
function saveEdit() {
var t = $scope.selectedItem;
$scope.listArray.$save(t).then(function(ref){
//console.log(ref);
});
}
};
UPDATE
After serious cross checking throughout my code i realised the issue is not from AngularFiire array. Even the workaround i did with the r.$watch and r.$loaded was unnecessary. the need for the work around was cause by another part of my code i didnt think was relevant.
I apologise for the mistake. I'd be deleting this question and a related one soon
Try using a watcher to reload the data:
var fireList = new Firebase("https://xxxxx.firebaseio.com/list");
var r = $firebaseArray(fireList);
r.$watch(function() {
r.$loaded(function () {
vm.list = r;
});
});
This is a common way of dealing with updates in an easy way, might solve your problem.
I'd like to have a paginated view of a collection. I tried using Backbone.Paginator but I just couldn't make it work.
I figured I'd do the pagination myself and I thought it would be a good idea to have my full collection, and then send the view a small collection of the big one, and do this every time someone clicks on 'next'.
I tried doing this but it doesn't work :
var purchaseCollection = new purchaseItemCollection({url:endpoints.purchases});
purchaseCollection.fetch();
var purchaseRangeCollection = new Backbone.Collection(purchaseCollection.models),
purchaseView = new purchaseItemCollectionView({collection:purchaseRangeCollection});
My second collection is only made of one model when it should have severals.
I'm wondering if this is even the best way to do it.
Any advice on how to split a collection into collections, or how to do it in another way would really be appreciated!
You could use a custom object to control a collection representing the list of models currently selected.
For example,
var Slicer = function(opts) {
opts || (opts = {});
// your big collection
this.collection = opts.collection || new Backbone.Collection();
// a collection filled with the currently selected models
this.sliced = new Backbone.Collection();
};
_.extend(Slicer.prototype, Backbone.Events, {
// a method to slice the original collection and fill the container
slice: function(begin, end) {
var models = this.collection.models.slice(begin, end);
this.sliced.reset(models);
// triggers a custom event for convenience
this.trigger('sliced', this.sliced);
}
});
You would then create an instance of this controller and either listen to the custom event sliced on this object or on a reset event on the sliced collection to update your view:
var controller = new Slicer({
collection: purchaseCollection
});
controller.on('sliced', function(c) {
console.log('sliced', c.pluck('id'));
});
controller.sliced.on('reset', function(c) {
console.log('reset', c.pluck('id'));
});
And a demo to play with http://jsfiddle.net/nikoshr/zjgkF/
Note that you also have to take into account the asynchronous nature of fetch, you can't immediately work on the models. In this setup, you would do something like
var purchaseCollection = new purchaseItemCollection(
[], // you have to pass an array
{url:endpoints.purchases} // and then your options
);
purchaseCollection.fetch().then(function() {
// do what you want
// for example
controller.slice(0, 10);
});
You can define the model of your full collection as another independent collection.
Then after fetch(), you will get your collections as the model of your full one.
var PurchaseCollection = Backbone.Collection.extend({
model: Backbone.Collection
})
var purchaseCollection = new PurchaseCollection({url:endpoints.purchases});
purchaseCollection.fetch()
purchaseCollection.each(function (purchaseItem, index) {
//the purchaseItem is what you want...
//do anything...
});
If you want a demo, click here.
Just remember that collection constructor has two attributes (http://backbonejs.org/#Collection-constructor). The first are the models and the second are the options like url etc.
I am working on a single-page-application. For this purpose, I am using Knockout.js, which is really great for this task.
Now I'm facing a problem: The content of the pages is appended with jQuerys append-function. When i append two detail-pages from the same template, i have a conflict with my viewmodel-object-names, since both declare it's offlineDemoDetailViewModel-variable under use of the same name.
TestDetailA (from TestDetail Template): offlineDemoDetailViewModel = offlineDemoDetailViewModel();
TestDetailB (from TestDetail Template): offlineDemoDetailViewModel = offlineDemoDetailViewModel();
What is the best way to handle this? Should i create the variable-name dynaically or is there a better way?
Thanks a lot!
Just for Info, here is my (test) offlineDemoDetailViewModel-code:
var offlineDemoDetailViewModel = function () {
var _viewmodel = new (function() {
this.uuid = ko.observable(localDatabase.createUUID());
});
return _viewmodel;
};
I'm new to Backbone.js, and someone who comes out of the 'standard' model of JS development I'm a little unsure of how to work with the models (or when).
Views seem pretty obvious as it emulates the typical 'listen for event and do something' method that most JS dev's are familiar with.
I built a simple Todo list app and so far haven't seen a need for the model aspect so I'm curious if someone can give me some insight as to how I might apply it to this application, or if it's something that comes into play if I were working with more complex data.
Here's the JS:
Todos = (function(){
var TodoModel = Backbone.Model.extend({
defaults: {
content: null
}
});
var TodoView = Backbone.View.extend({
el: $('#todos'),
newitem: $('#new-item input'),
noitems: $('#no-items'),
initialize: function(){
this.el = $(this.el);
},
events: {
'submit #new-item': 'addItem',
'click .remove-item': 'removeItem'
},
template: $('#item-template').html(),
addItem: function(e) {
e.preventDefault();
this.noitems.remove();
var templ = _.template(this.template);
this.el.append(templ({content: this.newitem.val()}));
this.newitem.val('').focus();
return this;
},
removeItem: function(e){
$(e.target).parent('.item-wrap').remove();
}
});
self = {};
self.start = function(){
new TodoView();
};
return self;
});
$(function(){
new Todos(jQuery).start();
});
Which is running here: http://sandbox.fluidbyte.org/bb-todo
Model and Collection are needed when you have to persist the changes to the server.
Example:
var todo = new TodoModel();
creates a new model. When you have to save the save the changes, call
todo.save();
You can also pass success and error callbacks to save . Save is a wrapper around the ajax function provided by jQuery.
How to use a model in your app.
Add a url field to your model
var TodoModel = Backbone.Model.extend({
defaults: {
content: null
},
url: {
"http://localhost";
}
});
Create model and save it.
addItem: function(e) {
e.preventDefault();
this.noitems.remove();
var templ = _.template(this.template);
this.el.append(templ({content: this.newitem.val()}));
this.newitem.val('').focus();
var todo = new TodoModel({'content':this.newitem.val()});
todo.save();
return this;
},
Make sure your server is running and set the url is set correctly.
Learning Resources:
Check out the annotated source code of Backbone for an excellent
explanation of how things fall into place behind the scenes.
This Quora question has links to many good resources and sample apps.
The model is going to be useful if you ever want to save anything on the server side. Backbone's model is built around a RESTful endpoint. So if for example you set URL root to lists and then store the list information in the model, the model save and fetch methods will let you save/receive JSON describing the mode to/from the server at the lists/<id> endpoint. IE:
ToDoListModel = Backbone.model.extend( {
urlRoot : "lists/" } );
// Once saved, lives at lists/5
list = new ToDoListModel({id: 5, list: ["Take out trash", "Feed Dog"] });
list.save();
So you can use this to interact with data that persists on the server via a RESTful interface. see this tutorial for more.
I disagree with the idea that model is needed only to persist changes (and I am including LocalStorage here, not only the server).
It is nice to have representation of models and collections so that you have object to work with and not only Views. In your example you are only adding and removing divs (html) from the page, which is something you can do normally with jQuery. Having a Model created and added to a Collection everytime you do "add" and maybe removed when you clear it will allow you some nice things, like for example sorting (alphabetically), or filtering (if you want to implement the concept of "complete" to-do).
In your code, for example:
var TodoModel = Backbone.Model.extend({
defaults: {
content: null
complete: false
}
});
var Todos = Backbone.Collection.extend({
model: TodoModel
})
In the View (irrelevant code is skipped):
// snip....
addItem: function(e) {
e.preventDefault();
this.noitems.remove();
var templ = _.template(this.template);
var newTodo = new TodoModel({ content: this.newitem.val() });
this.collection.add(newTodo); // you get the collection property from free from the initializer in Backbone
this.el.append(templ({model: newTodo})); // change the template here of course to use model
this.newitem.val('').focus();
return this;
},
Initialize like this:
self.start = function(){
new TodoView(new Todos());
};
Now you have a backing Collection and you can do all sort of stuff, like filtering. Let's say you have a button for filtering done todos, you hook this handler:
_filterDone: function (ev) {
filtered = this.collection.where({ complete: true });
this.el.html(''); // empty the collection container, I used "el" but you know where you are rendering your todos
_.each(filtered, function (todo) {
this.el.append(templ({model: todo})); // it's as easy as that! :)
});
}
Beware that emptying the container is probably not the best thing if you have events hooked to the inner views but as a starter this works ok.
You may need a hook for setting a todo done. Create a button or checkbox and maybe a function like this:
_setDone: function (ev) {
// you will need to scope properly or "this" here will refer to the element clicked!
todo = this.collection.get($(ev.currentTarget).attr('todo_id')); // if you had the accuracy to put the id of the todo somewhere within the template
todo.set('complete', true);
// some code here to re-render the list
// or remove the todo single view and re-render it
// in the simplest for just redrawr everything
this.el.html('');
_.each(this.collection, function (todo) {
this.el.append(templ({model: todo}));
});
}
The code above would not have been so easy without Models and Collections and as you can see it does not relate in any way with the server.