Knockout arrayFirst with MVC List - arrays

My MVC view model contains a number of properties including a list of objects.
This model is bound to a knockout model as follows:
viewModel = new DynamicModelLoading(#Html.Raw(Model.ToJson()));
ko.applyBindings(viewModel);
When looking at the knockout model I can see that my list has been successfully created as an array.
The problem I'm having is that whenever I use arrayFirst on the array it always returns null. I can create an observablearray in javascript and arrayFirst works fine.
var match = ko.utils.arrayFirst(viewModel.activeList(), function (item) {
return 2 === item.id;
});
Is there something I'm doing wrong to be able to apply arrayFirst on an array that has been bound from my MVC model?

Ok, I've finally sussed it. The mapper is creating the observable array as an array of objects full of observable properties. Therefore simply needed to state:
return 2 === item.id();
rather than return
2 === item.id;

Related

Selecting and accessing items in ng-repeat

I have an array of objects in a service that I want to display in a view like this
<li ng-repeat="item in filteredItems = (resource.items | filter:multipleFilters...">
<span class="title">{{item.escaped_name}}</span>
</li>
I want these objects to be selectable which is the easy part. Then I'd need to get the count of the selected items and be able to iterate over all of them to process/change data.
What is the best method to save and access the selected items?
Note that the selected items could change, for example a selected item could fall away due to changed filters. Also, I don't want to set a selected property on the objects in the array directly - the array of objects is in a service and used throughout the app in many lists and I don't want to "clean up" the selected property for each view.
I usually include a ng-click tag:
<li ng-repeat="item in ..." ng-click="select_item(item)">
The item passed to select_item() will be the one the user selected.
You can take the object oriented approach and create models to do your work for you basically. I've been in the same scenario and it's worked for me, plus I think it's a good tool angular gives you to work with. You would have a listModel and an itemModel - the list model would have a list of your single item itemModels. The list model you would use 1 instance of between where ever you are using this list of items. Take this with a grain of salt because this is just an example.
So you'd have the listModel
.factory('listModel', [singleItemModelInject,
function(singleItemModel) {
function listModel(items) {
this.items = _.map(items, listModel.create);
}
listModel.create = function(value, name) {
return new listModel(value);
};
listModel.prototype = {
get whatever() {
},
set whatever() {
}
}
return listModel;
}
]);
Notice it injects singleItemModel - this would be the individual item model it would look the same except it would have all your information on creation with what you pass it like
.factory('singleItemModel', [whateverYouNeedInjected,
function() {
function singleItemModel(item) {
this.name = item.name;
//default to not selected
this.selected = item.selected || false;
this.whateverElseYouNeed = item.whateverElseYouNeed
}
singleItemModel.create = function(value) {
return new singleItemModel(value);
};
So then you would have a single instance of the listModel you would use across your app, you can toggle a hide or show with whatever property, as long as you have setters and getters for your properties you want to access (like the name and isSelected or whatever you want) and have it 2 way bound, if it is changed to selected anywhere, it is universal because of the single instance you are using.
You can also you individual instances if you dont want the selected values to persist across the app, and only in that one page (or where ever you are using it)

Restangular how to update item in collection

I am currently fiddeling around with restangular and ui-router.
I do resolve a collection of items in my router which makes it available to the underlying controllers. I have a list of todos and i want to edit a todo. So i load a view where i can edit the item.
I get the model by $scope.todo = todos.get(id) I make a change to it and then i do $scope.todo.save() which updates the model on the server. But now i have the old item still in the collection of todos.
I want my collection to reflect the changes in the single item. I could delete the item from the collection and reinsert it afterwards, but this seems a little bit too complicated. Is there no easy way to update a model within a collection?
Update: Adding some Code
Note: The todos property gets resolved if the state is called.
If i edit a single todo i resolve it by
resolve : {
todo : function($stateParams, todos) {
return todos.get($stateParams.id);
}
}
I do some changes and then i call todo.save(). No changes will happen on the collection this way. I tried to do a todos.patch(todo) but that actually did a request to weird url and i guess it is intended to patch the whole collection (?)
I am sure there is a way to change a model within a collection, but i dont know how
After trying some stuff i ended up with replacing the item inside the collection. I created a little helper to lodash which i want to show here:
var replaceItemById = function(list, element) {
var index = _.indexOf(list, _.find(list, { id : element.id }));
list.splice(index, 1 , element);
return list;
};
_.mixin({'replaceItemById' : replaceItemById});
When i want to update a model inside a collection i do step by step:
Fetch the collection
Get a single item from the collection and edit it
Call save on the item
//The server returns the updated model
todo.save().then(function(editedTodo) {
_.replaceItemById(todos, editedTodo);
$state.go('todos.index');
});
This way i do not need to fetch the collection again (even if in most cases this is what you would do) and it is up to date after updating a single item.

Trying to add a collection to a model and render it in multiple places in a view

I'm trying to build an app that allows you to create items in a view in multiple places.
For instance, I can add a model from a collection when I create a new model in the parent collection.
The problem I'm having is, when I add the collection to the model and it iterates, it's adding the collection for each loop. So it ends up with LOTS of collections in the model that are repeated.
The parent model render has the following loop:
this.noteTasksViewAdding = new NoteTaskListViewAdding({ collection: tasks });
$('.note-tasks-list-all').append(this.noteTasksViewAdding.render().el);
this.collection.each(function(note){
var view = new NoteView({ model: note });
$('#items-list').prepend(view.render().el);
});
Then the model has the following render in it:
render: function() {
this.noteTasksViewAdding = new NoteTaskListViewAdding({ collection: tasks });
$('.note-tasks-list-all').append(this.noteTasksViewAdding.render().el);
this.$el.html(this.template(this.model.toJSON()));
return this;
}
What I want to have happen is that the collection is added to the model when it's rendered. I'm open to any suggestions on how to do this better.
Thanks!
I faced the problem as well. The solution is to clear the view before you set the collection. In your case, when you set parent view, you might do this:
$('.note-tasks-list-all').html(this.noteTasksViewAdding.render().el);
Then you can append your collection members.

How to make Backbones toJSON function include sub-models and collections?

I have a few models that don't just contain basic data attributes, but they might have one or two attributes that hold another models object.
This has been okay, but now I want to call
myRootModel.toJSON()
and I've noticed that it doesn't call .toJSON on the other models in my model that I'm trying to call toJSON() on.
Is there a way to override backbone model .toJSON to go through all fields, recursively, whether they are basic attributes, sub-models or collections? If not, can I override toJSON in each model / collection?
I'm aware of backbone-relational, but I don't want to go that route - I'm not using fetch/save, instead our API returns responses that I adjust in the models parse function and simply invoke new MyRootModel(data,{parse:true}).
Here's a way you can achieve such a thing (there's maybe another way):
Backbone.Model.prototype.toJSON = function() {
var json = _.clone(this.attributes);
for(var attr in json) {
if((json[attr] instanceof Backbone.Model) || (json[attr] instanceof Backbone.Collection)) {
json[attr] = json[attr].toJSON();
}
}
return json;
};
http://jsfiddle.net/2Asjc/.
Calling JSON.parse(JSON.stringify(model)) parses the model with all the sub-models and sub-collections recursively. Tried on Backbone version 1.2.3.

How to clone a backbone collection

Is there a way to easily clone Backbone Collection? I wonder why there is no build in method like for models. My problem is that I have a model holding a collection of childs. When I clone the model. I've still the collection of childs but only with their default values.
Simplest way:
var cloned = new Backbone.Collection(original.toJSON());
where original is the collection to clone.
Could always then extend Backbone's Collection to add clone support w or w/o inheritance support.
What's your use case that you want to clone the collection?
There isn't a built in clone function for a collection because you do not want to clone the models within the collection. Cloning a model would cause there to be two separate instances of the same model, and if you update one model, the other one won't be updated.
If you want to create a new collection based upon a certain criteria, then you can use the collection's filter method.
var freshmenModels = studentsCollection.filter(function(student) {
return student.get('Year') === 'Freshman';
}
var freshmenCollection = new Backbone.Collection(freshmenModels);
To go ahead and clone the models in the collection, you can write the following code
var clonedCollection = new Backbone.Collection();
studentsCollection.each(function(studentModel) {
clonedCollection.add(new Backbone.Model(studentModel.toJSON()));
});
Use the Backbone Collection clone() method:
var clonedCollection = myCollection.clone();
Another option, if you need the following (which is what I was looking for when I found this question ;) ):
The copy of the collection should be of the same type as the original collection (e.g. you've created your own collection type that extends Backbone.Collection)
The copy of the collection should be created with the same options as the original
The models in the copy of the collection should be created using the model.clone() method
Code:
var models = original.map(function (model) { return model.clone(); });
var options = _.clone(original.options);
var copy = new original.constructor(models, options);
A generic clone method on Backbone.Collection would be awkward because there are always going to be subtleties around whether models and their nested objects get copied by reference or are themselves cloned. Requirements will vary wildly according to your scenario, so it's been left for you to write what you need.

Resources