Related
I have followed a tutorial (source code) and everything works great but I have one issue, the sorting works but how do I add another sorting option?
For example I have this
server_api: {
'per_page': function() { return this.perPage },
'page': function() { return this.currentPage },
'year': function() {
if (this.sortField === undefined)
return '2016';
return this.sortField;
}
},
So I can sort my API using year, but my API can also accept another parameter like sort_by.
So I added this under year:
'sort_by': function() {
if(this.sortField === undefined)
return 'title.desc';
return this.sortField;
}
Now every time I click the 'year button', it sorts based on year example:
sort_by=title.desc&year=2016
sort_by=title.desc&year=2011
but if click on sort_by button, it's changing the value of year, instead of sort_by example:
sort_by=title.desc&year=popularity.asc
My full code:
<script type="text/html" id="sortingTemplate">
<div class="form-group">
<div class="col-sm-3">
<div class="btn-group">
<button data-toggle="dropdown" class="btn btn-default dropdown-toggle">Year <strong><span id="sortByYear">2016</span></strong> <span class="caret"></span></button>
<ul class="dropdown-menu" id="year">
<li>2016</li>
<li>2015</li>
<li>2014</li>
</ul>
</div>
</div>
<div class="col-sm-3">
<div class="btn-group">
<button data-toggle="dropdown" class="btn btn-default dropdown-toggle">Sort by <strong><span id="sortBy">2016</span></strong> <span class="caret"></span></button>
<ul class="dropdown-menu" id="sort_by">
<li>Popularity Descending</li>
<li>Popularity Ascending</li>
<li>Rating Descending</li>
<li>Rating Ascending</li>
<li>Release Date Descending</li>
<li>Release Date Ascending</li>
<li>Title (A-Z)</li>
<li>Title (Z-A)</li>
</ul>
</div>
</div>
</div>
</script>
<script>
window.myapp = {};
myapp.collections = {};
myapp.models = {};
myapp.views = {};
myapp.serverURL = '{{url("/")}}';
myapp.models.Item = Backbone.Model.extend({});
myapp.collections.PaginatedCollection = Backbone.Paginator.requestPager.extend({
model: myapp.models.Item,
paginator_core: {
dataType: 'json',
url: '{{ route('api.discover.movie') }}'
},
paginator_ui: {
firstPage: 1,
currentPage: 1,
perPage: 20,
totalPages: 10
},
server_api: {
'per_page': function() { return this.perPage },
'page': function() { return this.currentPage },
'year': function() {
if(this.sortField === undefined)
return '2016';
return this.sortField;
},
'sort_by': function(){
if (this.sortField2 === undefined)
return 'title.desc';
return this.sortField2;
}
},
parse: function (response) {
$('#movies-area').spin(false);
this.totalRecords = response.total;
this.totalPages = Math.ceil(response.total / this.perPage);
return response.data;
}
});
myapp.views.ItemView = Backbone.View.extend({
tagName: 'div',
className: 'col-lg-2',
template: _.template($('#MovieItemTemplate').html()),
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('remove', this.remove, this);
},
render : function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
myapp.views.SortedView = Backbone.View.extend({
events: {
'click #year a': 'updateYear',
'click #sort_by': 'updateSortBy'
},
template: _.template($('#sortingTemplate').html()),
initialize: function () {
this.collection.on('reset', this.render, this);
this.collection.on('sync', this.render, this);
this.$el.appendTo('#discover');
},
render: function () {
var html = this.template(this.collection.info());
this.$el.html(html);
if (this.collection.sortField == undefined){
var sortYearText = this.$el.find('#sortByYear').text();
}else{
var sortYearText = this.collection.sortField;
}
$('#sortByYear').text(sortYearText);
if (this.collection.sortField2 == undefined){
var sortByText = this.$el.find('#sortBy').text();
}else{
var sortByText = this.collection.sortField2;
}
$('#sortBy').text(sortByText);
},
updateYear: function (e) {
e.preventDefault();
var currentYear = $(e.target).attr('href');
this.collection.updateOrder(currentYear);
$('#movies-area').spin();
},
updateSortBy: function (e) {
e.preventDefault();
var currentSort = $(e.target).attr('href');
this.collection.updateOrder(currentSort);
$('#movies-area').spin();
}
});
myapp.views.PaginatedView = Backbone.View.extend({
events: {
'click button.prev': 'gotoPrev',
'click button.next': 'gotoNext',
'click a.page': 'gotoPage'
},
template: _.template($('#paginationTemplate').html()),
initialize: function () {
this.collection.on('reset', this.render, this);
this.collection.on('sync', this.render, this);
this.$el.appendTo('#pagination');
},
render: function () {
var html = this.template(this.collection.info());
this.$el.html(html);
},
gotoPrev: function (e) {
e.preventDefault();
$('#movies-area').spin();
this.collection.requestPreviousPage();
},
gotoNext: function (e) {
e.preventDefault();
$('#movies-area').spin();
this.collection.requestNextPage();
},
gotoPage: function (e) {
e.preventDefault();
$('#movies-area').spin();
var page = $(e.target).text();
this.collection.goTo(page);
}
});
myapp.views.AppView = Backbone.View.extend({
el : '#paginated-content',
initialize : function () {
$('#movies-area').spin();
var items = this.collection;
items.on('add', this.addOne, this);
items.on('all', this.render, this);
items.pager();
},
addOne : function ( item ) {
var view = new myapp.views.ItemView({model:item});
$('#paginated-content').append(view.render().el);
}
});
$(function(){
myapp.collections.paginatedItems = new myapp.collections.PaginatedCollection();
myapp.views.app = new myapp.views.AppView({collection: myapp.collections.paginatedItems});
myapp.views.pagination = new myapp.views.PaginatedView({collection:myapp.collections.paginatedItems});
myapp.views.sorting = new myapp.views.SortedView({collection:myapp.collections.paginatedItems});
});
</script>
Quickfix
Change the values directly in the view's events callbacks:
updateYear: function(e) {
e.preventDefault();
var currentYear = $(e.target).attr('href');
this.collection.sortField = currentYear;
$('#movies-area').spin();
},
updateSortBy: function(e) {
e.preventDefault();
var currentSort = $(e.target).attr('href');
this.collection.sortField2 = currentSort;
$('#movies-area').spin();
}
Better way
Name things with what they represent and encapsulate the logic.
In the collection, offer clearly named setters.
server_api: {
/* ...snip... */
'year': function() {
return this.year || '2016';
},
'sort_by': function() {
return this.sortField || 'title.desc';
}
},
setYearFilter: function(value) {
if (value !== undefined) {
this.year = value;
return this.pager(options);
}
return reject();
},
And use them in the view:
updateYear: function(e) {
e.preventDefault();
var currentYear = $(e.target).attr('href');
this.collection.setYearFilter(currentYear)
$('#movies-area').spin();
},
updateSortBy: function(e) {
e.preventDefault();
var currentSort = $(e.target).attr('href');
this.collection.updateOrder(currentSort);
$('#movies-area').spin();
}
Best way
Update to the latest version of backbone.paginator, not that it will solve the problem directly, but it'll be easier to find help and documentation. Also, additional features!
I've got a Backbone.View that renders a collection and filters it on mouse click. I need to add class active to the button that I click, but the problem is that buttons are the part of this view and whenever I try to addClass or toggleClass it just renders again with default class. Here's my view:
var ResumeList = Backbone.View.extend({
events: {
'click #active': 'showActive',
'click #passed': 'showPassed'
},
initialize: function () {
this.collection = new ResumeCollection();
},
render: function (filtered) {
var self = this;
var data;
if (!filtered) {
data = this.collection.toArray();
} else {
data = filtered.toArray();
}
this.$el.html(this.template({ collection: this.collection.toJSON() });
_.each(data, function (cv) {
self.$el.append((new ResumeView({model: cv})).render().$el);
});
return this;
},
showActive: function () {
this.$('#active').toggleClass('active');
// a function that returns a new filtered collection
var filtered = this.collection.filterActive();
this.render(filtered);
}
});
But as I've already told, the class I need is toggled or added just for a moment, then the view is rendered again and it is set to default class. Is there any way to handle this?
I simplified the rendering and added some optimizations.
Since we don't have your template, I changed it to enable optimization:
<button id="active" type="button">Active</button>
<button id="passed" type="button">Passed</button>
<div class="list"></div>
Then your list view could be like this:
var ResumeList = Backbone.View.extend({
events: {
'click #active': 'showActive',
'click #passed': 'showPassed'
},
initialize: function() {
this.childViews = [];
this.collection = new ResumeCollection();
},
render: function() {
this.$el.html(this.template());
// cache the jQuery element once
this.elem = {
$list: this.$('.list'),
$active: this.$('#active'),
$passed: this.$('#passed')
};
this.renderList(); // default list rendering
return this;
},
renderList: function(collection) {
this.elem.$list.empty();
this.removeChildren();
collection = collection || this.collection.models;
// Underscore's 'each' has a argument for the context.
_.each(collection, this.renderItem, this);
},
renderItem: function(model) {
var view = new ResumeView({ model: model });
this.childViews.push(view);
this.elem.$list.append(view.render().el);
},
showActive: function() {
this.elem.$active.toggleClass('active');
var filtered = this.collection.filterActive();
this.renderList(filtered);
},
/**
* Gracefully call remove for each child view.
* This is to avoid memory leaks with listeners.
*/
removeChildren: function() {
var view;
while ((view = this.childViews.pop())) {
view.remove();
}
},
});
Additional information:
Managing Views and Memory Leaks
Underscore's each (notice the third argument)
Try to avoid callback hell, make the callbacks reusable (like renderItem)
I have edited the snippet can you try this.
var ResumeList = Backbone.View.extend({
events: {
'click #active': 'filterActive',
'click #passed': 'showPassed'
},
toggleElement: undefined,
initialize: function () {
this.collection = new ResumeCollection();
},
render: function (filtered) {
var self = this;
var data;
if (!filtered) {
data = this.collection.toArray();
} else {
data = filtered.toArray();
}
this.$el.html(this.template({ collection: this.collection.toJSON() });
_.each(data, function (cv) {
self.$el.append((new ResumeView({model: cv})).render().$el);
});
return this;
},
filterActive: function (evt) {
this.toggleElement = this.$el.find(evt.currentTarget);
// a function that returns a new filtered collection
var filtered = this.collection.filterActive();
this.render(filtered);
this.toggleActive();
},
toggleActive: function() {
if(this.toggleElement.is(':checked')) {
this.$el.find('#active').addClass('active');
} else {
this.$el.find('#active').removeClass('active');
}
}
});
Please note: I have taken checkbox element instead of button.
function Employee() {
var self = this;
self.name = ko.observable("John");
}
ko.bindingHandlers.test = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// implementation
}
}
<div data-bind="test: name"></div>
Is there a way to get the observable name? not the value of the observable.
TIA.
Update:
This is the code snippet.
function ViewModel() {
var self = this;
$.ajax({
type: type,
url: url,
success: function (data) {
ko.mapping.fromJS(data, {} , self);
}
});
self.item = ko.observable(self.my_item);
self.selectedItem = ko.observable();
}
ko.bindingHandlers.item = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
$el = $(element);
var propName = allBindings().name;
var val = ko.unwrap(valueAccessor());
$el.attr("src", val);
$el.click(function () {
viewModel.selectedItem(propName);
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
$el = $(element);
var ops = allBindings().name;
var val = ko.unwrap(valueAccessor());
$el.attr("src", val);
}
};
ko.bindingHandlers.selectItem = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
$el = $(element);
$el.attr("src", valueAccessor());
$el.click(function () {
bindingContext.$data.item()[ko.unwrap(bindingContext.$data.selectedItem)](valueAccessor());
});
}
};
<img height="25" width="25" data-bind="item: item().img1, name: 'img1'" />
<img height="20" width="20" data-bind="selectItem: '/images/myimage1.png'" />
<img height="20" width="20" data-bind="selectItem: '/images/myimage2.png'" />
<img height="20" width="20" data-bind="selectItem: '/images/myimage3.png'" />
When you click images that has selectItem the first image should replaced its src attribute. If you have better way to do this please suggest.
FYI, the properties inside items observables are link of images.
TIA.
You are getting ahead of yourself with the custom binding.
The bottom line is: You don't need a custom binding for what you want to do. It's easy - if you don't make it complicated:
function loadImages() {
// return $.get(url);
// mockup Ajax response, in place of a real $.get call
return $.Deferred().resolve({
items: [
{height: 20, width: 20, src: 'http://placehold.it/150/30ac17', title: 'image 1'},
{height: 20, width: 20, src: 'http://placehold.it/150/412ffd', title: 'image 2'},
{height: 20, width: 20, src: 'http://placehold.it/150/c672a0', title: 'image 3'}
]
}).promise();
}
function ImageList() {
var self = this;
// data
self.items = ko.observableArray();
self.selectedItem = ko.observable();
// init
loadImages().done(function (data) {
ko.mapping.fromJS(data, {}, self);
});
}
ko.applyBindings(new ImageList())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<div data-bind="with: selectedItem">
<img data-bind="attr: {height: 25, width: 25, src: src}">
</div>
<div data-bind="foreach: items">
<img data-bind="attr: {height: height, width: width, src: src}, click: $root.selectedItem" />
</div>
<hr>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
Note how I use selectedItem as a click event handler. This is possible because in event handlers, knockout passes the relevant object (in this case, an image object from the array) as the first argument. Conveniently, observables set their value to the first argument you call them with. And presto: You have click event handler that sets the last clicked object.
EDIT
"I need multiple selected item then my items are just my context menu not just one selected item."
function loadImages() {
// return $.get(url);
// mockup Ajax response, in place of a real $.get call
return $.Deferred().resolve({
items: [
{height: 20, width: 20, src: 'http://placehold.it/150/30ac17', title: 'image 1'},
{height: 20, width: 20, src: 'http://placehold.it/150/412ffd', title: 'image 2'},
{height: 20, width: 20, src: 'http://placehold.it/150/c672a0', title: 'image 3'}
]
}).promise();
}
function ImageList() {
var self = this;
// data
self.items = ko.observableArray();
self.selectedItems = ko.observableArray();
// init
loadImages().done(function (data) {
ko.mapping.fromJS(data, {}, self);
});
self.selectItem = function (item) {
var pos = ko.utils.arrayIndexOf(self.selectedItems(), item);
if (pos === -1) self.selectedItems.push(item);
};
self.deselectItem = function (item) {
var pos = ko.utils.arrayIndexOf(self.selectedItems(), item);
if (pos !== -1) self.selectedItems.remove(item);
};
}
ko.applyBindings(new ImageList())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<div data-bind="foreach: selectedItems">
<img data-bind="attr: {height: 25, width: 25, src: src}, click: $root.deselectItem">
</div>
<div data-bind="foreach: items">
<img data-bind="attr: {height: height, width: width, src: src}, click: $root.selectItem" />
</div>
<hr>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
<div data-bind="foreach: {data: skills, as: 'skill'}" >
<div data-bind="foreach: Object.keys(skill)" >
<a data-bind="text: $data"></a> : <a data-bind="text: skill[$data]"></a>
</div>
</div>
v = new function AppViewModel() {
this.skills = [{rates:"sdfdcvxcsd", cat: 2, car:55}, {color:"sdfdcvxcsd", zoo: 2,boat:55}];
}
ko.applyBindings(v);
Try something like this
view:
<div data-bind="test:name,propertyName:'name'"></div>
viewModel:
ko.bindingHandlers.test = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var propertyName = allBindings().propertyName; //property name here
ko.bindingHandlers.text.update(element, valueAccessor);
alert(propertyName)
}
};
function Employee() {
var self = this;
self.name = ko.observable("John");
}
ko.applyBindings(new Employee());
working fiddle here
This will get you the observable name.
This converts the valueAccessor (function(){return name }) to a string which is then split to remove the observable name.
ko.bindingHandlers.GetObservableName = {
init: function (element, valueAccessor) {
var observableName = String(valueAccessor).split(' ')[1];
alert(observableName);
}
};
function Employee() {
var self = this;
self.name = ko.observable("John");
}
<div data-bind="GetObservableName: name"></div>
Here is a JSFiddle
The index of the split method in the fiddle is different to the one in the example above. The above works for me in Visual Studio 2013.
Thanks
Now Solved - See bottom....
I've got a Backbone list view with a button on it that should show the edit elements.
Neither the jQuery hide() call in the 'showAddEntry' function or the view rendering for 'versionEditView' are doing anything at all. I've stepped right through and I'm not getting any errors. I've even tried manually running methods in the console to see what's going on with hide, but I'm not getting anywhere.
Here's the main view...
define(['ministry', 'jquery', 'models/m-version-info', 'views/about/v-edit-version-info-entry', 'text!templates/version-info/version-info.html'],
function(Ministry, $, VersionInfo, VersionInfoEditView, TemplateSource) {
var versionInfoEntriesView = Ministry.View.extend({
el: '#mainAppArea',
template: Handlebars.compile(TemplateSource),
versionInfoEditView: null,
initialize: function () {
this.$addEntryArea = $('#addVersionInfoEntryArea');
this.$addEntryButton = $('#addVersionInfoEntryButton');
},
events: {
'click #addVersionInfoEntryButton': 'showAddEntry'
},
render: function () {
var that = this;
var entries = new VersionInfo.Collection();
entries.fetch({
success: function (data) {
that.$el.html(that.template({ items: data.toJSON() }));
}
});
return this;
},
showAddEntry: function() {
if (this.versionInfoEditView != null) {
this.versionInfoEditView.trash();
}
this.versionInfoEditView = new VersionInfoEditView({ el: this.$addEntryArea });
this.$addEntryButton.hide();
this.versionInfoEditView.render();
return false;
}
});
return versionInfoEntriesView;
});
And here's the child view...
define(['ministry', 'models/m-version-info', 'text!templates/version-info/edit-version-info- entry.html', 'jquery.custom'],
function (Ministry, VersionInfo, TemplateSource) {
var editVersionInfoView = Ministry.View.extend({
template: Handlebars.compile(TemplateSource),
initialize: function () {
this.$dbVersionInput = this.$('#dbVersion');
this.$tagInput = this.$('#tag');
},
render: function () {
this.$el.html(this.template());
return this;
},
events: {
'submit .edit-version-info-form': 'saveEntry'
},
saveEntry: function() {
var entry = new VersionInfo.Model({ dbVersion: this.$dbVersionInput.val(), tag: this.$tagInput.val() });
entry.save({
success: function() {
alert('Your item has been saved');
}
});
return false;
}
});
return editVersionInfoView;
});
And the main template...
<h2>Version Info</h2>
<div id="info">
<a id="addVersionInfoEntryButton" href="#/versioninfo">Add manual entry</a>
<div id="addVersionInfoEntryArea">
</div>
<ul id="items">
{{#each items}}
<li>{{dbVersion}} | {{tag}}</li>
{{/each}}
</ul>
</div>
And the edit template...
<form class="edit-version-info-form">
<h3>Create a new entry</h3>
<label for="dbVersion">DB Version</label>
<input type="text" id="dbVersion" maxlength="10" />
<label for="tag">Tag</label>
<input type="text" id="tag" />
<button type="submit" id="newEntryButton">Create</button>
</form>
I'm fairly new to backbone so I may well be doing something totally wrong, but I can't see anything wrong with the approach so far and it's not throwing any errors.
OK - Fix as follows after some facepalming...
define(['ministry', 'jquery', 'models/m-version-info', 'views/about/v-edit-version-info-entry', 'text!templates/version-info/version-info.html'],
function(Ministry, $, VersionInfo, VersionInfoEditView, TemplateSource) {
var versionInfoEntriesView = Ministry.View.extend({
el: '#mainAppArea',
template: Handlebars.compile(TemplateSource),
versionInfoEditView: null,
$addEntryArea: undefined,
$addEntryButton: undefined,
initialize: function () {
},
events: {
'click #addVersionInfoEntryButton': 'showAddEntry'
},
render: function () {
var that = this;
var entries = new VersionInfo.Collection();
entries.fetch({
success: function (data) {
that.$el.html(that.template({ items: data.toJSON() }));
that.$addEntryArea = that.$('#addVersionInfoEntryArea');
that.$addEntryButton = that.$('#addVersionInfoEntryButton');
}
});
return this;
},
showAddEntry: function (e) {
e.preventDefault();
if (this.versionInfoEditView != null) {
this.versionInfoEditView.trash();
}
this.versionInfoEditView = new VersionInfoEditView({ el: this.$addEntryArea });
this.$addEntryButton.hide();
this.$addEntryArea.append('Do I want to put it here?');
this.versionInfoEditView.render();
}
});
return versionInfoEntriesView;
});
The issue was due to the fact that I was setting the internal element variables within the view before the completion of the render, so the elements were linked up to nothing. I resolved this by extracting the element initiation to the end of the render success callback.
Here's the fix again...
define(['ministry', 'jquery', 'models/m-version-info', 'views/about/v-edit-version-info-entry', 'text!templates/version-info/version-info.html'],
function(Ministry, $, VersionInfo, VersionInfoEditView, TemplateSource) {
var versionInfoEntriesView = Ministry.View.extend({
el: '#mainAppArea',
template: Handlebars.compile(TemplateSource),
versionInfoEditView: null,
$addEntryArea: undefined,
$addEntryButton: undefined,
initialize: function () {
},
events: {
'click #addVersionInfoEntryButton': 'showAddEntry'
},
render: function () {
var that = this;
var entries = new VersionInfo.Collection();
entries.fetch({
success: function (data) {
that.$el.html(that.template({ items: data.toJSON() }));
that.$addEntryArea = that.$('#addVersionInfoEntryArea');
that.$addEntryButton = that.$('#addVersionInfoEntryButton');
}
});
return this;
},
showAddEntry: function (e) {
e.preventDefault();
if (this.versionInfoEditView != null) {
this.versionInfoEditView.trash();
}
this.versionInfoEditView = new VersionInfoEditView({ el: this.$addEntryArea });
this.$addEntryButton.hide();
this.$addEntryArea.append('Do I want to put it here?');
this.versionInfoEditView.render();
}
});
return versionInfoEntriesView;
});
The issue was due to the fact that I was setting the internal element variables within the view before the completion of the render, so the elements were linked up to nothing. I resolved this by extracting the element initiation to the end of the render success callback.
I'm having issues with my knockoutjs implementation. Seems to be working fine on Chrome and Safari IE and FF have thrown a hissy fit.
The message which I encounter is as follows:
Unable to parse bindings. Message: TypeError: 'AccountName' is
undefined; Bindings value: value: AccountName
The issue is happening within a script tag which serves as a knockout template:
<div id="newAccountDialog" class="dialog" data-bind="dialog: { autoOpen: false, resizable: false, modal: true, width: 350, title: 'Exchange Account'}, template: { name: 'dialogFormTemplate', data: CurrentAccount }, openDialog: IsNew"></div>
<script id="dialogFormTemplate" type="text/html">
<form id="dialogForm">
<h1>Exchange Account Manager</h1>
<p>Add new or edit an existing exchange account settings.</p>
<label for="AccountName">
Account
</label>
<input id="AccountName" name="AccountName" type="text" data-bind="value: AccountName, valueUpdate: 'afterkeydown'" class="ui-widget-content ui-corner-all" />
<div class="buttonsContainer floatRight">
<button id="Save" data-bind="click: $root.SaveAccount, dialogcmd: { id: 'newAccountDialog', cmd: 'close'}, jqButton: { icons: { primary: 'ui-icon-disk' } }">Save & Close</button>
</div>
</form>
</script>
I assume some sort of early binding is being triggered on the template
data : CurrentAccount
where an undefined / null is being passed into CurrentAccount. I have seen this issue outside of script tags, but only if the observable is not defined or null.
My viewmodel looks as following:
var AccountModel = function () {
var self = this;
self.Accounts = ko.observableArray([]);
self.CurrentAccount = ko.observable(null);
self.IsNew = ko.observable(false);
self.LoadAccounts = function () {
$account.invoke("GetAccounts", {}, function (data) {
var mapped = $.map(data, function (item) {
var account = new Account(item);
var innerMapped = $.map(item.Mailboxes, function (mailbox) {
return new Mailbox(mailbox);
});
account.Mailboxes(innerMapped);
return account;
});
self.Accounts(mapped);
});
}
self.EditAccount = function (data) {
self.CurrentAccount(data);
self.IsNew(true);
}
self.SaveAccount = function () {
if (self.CurrentAccount().Id() <= 0) {
$account.invoke('AddAccount', ko.toJS(self.CurrentAccount()), function (data) {
self.Accounts.push(new Account(data));
self.CurrentAccount(new Account(data));
self.IsNew(true);
});
} else {
$account.invoke('UpdateAccount', ko.toJS(self.CurrentAccount()), function (data) {
//self.CurrentAccount(new Account(data));
});
}
}
self.CreateAccount = function () {
self.IsNew(true);
var account = { Id: 0, AccountName: '', IsNTLM: -1, Email: '', Password: '', Domain: 'mydomain', ExchangeVersion: 1, Mailboxes: [] };
self.CurrentAccount(new Account(account));
}
};
My dialog bindingHandler is defined as follows:
ko.bindingHandlers.dialog = {
init: function (element, valueAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {};
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).dialog('destroy');
});
$(element).dialog(options);
}
};
I have ommited the Account object, as it is possibly not required in this context.
I would appreciate any help.
Thank you in advance.
There is no "early" binding in Knockout. Everything is bound when you call ko.applyBindings. But certain bindings can stop or delay binding of their descendant elements. template is one of those when you use the if or ifnot options. In your case, you can use the if option like this:
template: { name: 'dialogFormTemplate', data: CurrentAccount, 'if': CurrentAccount }
Note: The quotes around if are required in some older browsers.