I am bit new to knockout and jquery mobile, There was a question which is already answered, I need to optimize the PageStateManager class to use generic bindings, currently PageStateManager can only use for one binding,I would really appreciate if someone can guide me to create a generic class to manage page states with knockout bindings Heere is the working code,http://jsfiddle.net/Hpyca/14/
PageStateManager = (function () {
var viewModel = {
selectedHospital: ko.observable()
};
var changePage = function (url, viewModel) {
console.log(">>>>>>>>" + viewModel.id());
$.mobile.changePage(url, {viewModel: viewModel});
};
var initPage = function(page, newViewModel) {
viewModel.selectedHospital(newViewModel);
};
var onPageChange = function (e, info) {
initPage(info.toPage, info.options.viewModel);
};
$(document).bind("pagechange", onPageChange);
ko.applyBindings(viewModel, document.getElementById('detailsView'));
return {
changePage: changePage,
initPage: initPage
};
})();
Html
<div data-role="page" data-theme="a" id="dashBoardPage" data-viewModel="dashBoardViewModel">
<button type="button" data-bind="click: goToList">DashBoard!</button>
</div>
New dashboard model
var dashBoardViewModel = function() {
var self = this;
self.userName = ko.observable('Welcome! ' + "UserName");
self.appOnline = ko.observable(true);
self.goToList = function(){
//I would like to use PageStateManager here
// PageStateManager.changePage($("#firstPage"),viewModel);
ko.applyBindings(viewModel,document.getElementById("firstPage"));//If I click Dashbord button multiple times it throws and multiple bind exception
$.mobile.changePage($("#firstPage"));
}
}
ko.applyBindings(dashBoardViewModel,document.getElementById("dashBoardPage"));
update url : http://jsfiddle.net/Hpyca/14/
Thank you in advance
I would probably go for creating a NavigationService which only handles changing the page and let knockout and my view models handle the state of the pages.
An simple example of such a NavigationService could be:
function NavigationService(){
var self = this;
self.navigateTo = function(pageId){
$.mobile.changePage($('#' + pageId));
};
}
You could then, in your view models just call it when you want it to navigate to a new page. One example would be upon selection of a hospital (which could be done either via a selection function or by manually subscribing to changes to the selectedHospital observable):
self.selectHospital = function(hospital){
self.selectedHospital(hospital);
navigationService.navigateTo('detailsView');
};
Other than the call to the navigationService to navigate, it's just ordinary knockout to keep track of which viewmodel should be bound where. A lot easier than having jquery mobile keeping track of which viewmodel goes where, if you ask me.
I have updated your jsfiddle to show a sample of how this could be done, making as few changes as possible to the HTML code. You can find the updated fiddle at http://jsfiddle.net/Hpyca/15/
Related
I'm building a custom wizard in knockout that dynamically loads knockout components during each "step" of the wizard. I've managed to get all of this working without much hassle, and it seems to work pretty well.
However, I'm wanting to implement some callbacks within the wizard when certain events happen. For example, before and after navigation.
Currently, one of my navigation functions looks like this:
this.goNext = function () {
if (!this.canGoNext()) return;
this.currentStep(this.pages()[this.currentIndex() + 1]);
this.loadPage();
}
I would like to build 2 callback functions called beforePageChange and onPageChange.
My general assumption is that beforePageChange would pass in a couple parameters, notably the current page and the next page. However, I also want it to be able to be observed from any other class utilization the wizard.
For example, on my parent page I would have something like:
this.wizard = Site.loadWizard(arguments);
this.wizard.beforePageChange(function(options) {
if (!options.currentPage.complete) return false;
// do stuff
return true;
});
In turn the wizard would execute its navigation commands and trigger the appropriate callbacks.
I feel like there's something I'm just fundamentally missing here.
Edit
My current version works as follows:
In the wizard:
this.canChangePage = ko.obserable(true);
this.beforePageChange = function (options) {
};
this.beforePageChangeHandler = function (options) {
this.beforePageChange(options);
// do stuff
return true;
};
this.onPageChange = function (options) {
};
this.onPageChangeHandler = function (options) {
this.onPageChange(options);
//do stuff
return true;
}
On the page implementing the wizard:
this.wizard = Site.loadComponent(params, function () {
this.wizard.beforePageChange = function (options) {
this.canChangePage(false);
};
}.bind(this));
I'm not sure if there's a better way to implement this, or if this is the best solution.
The solution Tomalak described in their comment (I think):
Since you already have access to the wizard instance, you can subscribe to its currentStep observable. To get notifications before it changes, you pass a third parameter: "beforeChange". (The second is the this context).
var Wizard = function() {
this.currentStep = ko.observable(0);
}
Wizard.prototype.next = function() {
this.currentStep(this.currentStep() + 1);
}
Wizard.prototype.prev = function() {
this.currentStep(this.currentStep() - 1);
}
var Page = function() {
this.wizard = new Wizard();
this.wizard.currentStep.subscribe(function(oldStep) {
console.log("Page work before step change from step", oldStep);
}, this, "beforeChange");
this.wizard.currentStep.subscribe(function(newStep) {
console.log("Page work after step change to", newStep);
});
}
ko.applyBindings(new Page());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="with:wizard">
<button data-bind="click: prev">back</button>
<span data-bind="text: currentStep"></span>
<button data-bind="click: next">next</button>
</div>
I'm trying to get a div to fade out and then change a session variable which is being used in the template. The session variable is being successfully changed in the callback function but the template is not reactively updating.
The following does not reactively update the template. (These are trigger)
$(event.target.parentNode).find(subclass)
.fadeOut("slow", function() {
Session.set(this.valueOf() + "_show_exercise_fields", set_show_exercise_fields);
The following does reactively update the template.
Session.set(this.valueOf() + "_show_exercise_fields", set_show_exercise_fields);
$(event.target.parentNode).find(subclass)
.fadeOut("slow", function() {
// do nothing
});
Is there a way to force the template to re render or a better way to do what I am trying to do. Thanks
EDIT 1
Below is the entire function
Template.exercise.events({
'click .exercise-name': function(event) {
var subclass = ".exercise-fields-container";
var set_show_exercise_fields = false;
if (!Session.get(this.valueOf() + "_show_exercise_fields")) {
var subclass = ".exercise-options-container";
var set_show_exercise_fields = true;
}
// find the subclass (either the fields container or the options
// container) and fade out
$(event.target.parentNode).find(subclass)
.fadeOut("slow", function() {
Session.set(this.valueOf() + "_show_exercise_fields", set_show_exercise_fields);
});
}
});
Template.exercise.helpers({
show_fields: function() {
Session.setDefault(this.valueOf() + "_show_exercise_fields", true);
return Session.get(this.valueOf() + "_show_exercise_fields");
}
});
Below is the template
<template name="exercise">
<div class="exercise-name">
{{this.name}}
</div>
{{#if show_fields}}
Fields
{{else}}
Options
{{/if}}
</template>
Event handlers aren't reactive contexts. You can create a reactive context using Tracker.autorun().
If you use a session variable within the function you pass to autorun, the entire function will rerun whenever the session variable is changed. In this context you could fade in or out as you desire.
I had a scenario where a collection was being updated, so I had to re-build my select element using Materialize Select
Here's what my on rendered function looks like. The autorun knows that Channels is a reactive data source and re-runs the autorun function when this data source changes.
Channels = new Mongo.Collection("channels");
Template.channelSelectController.onRendered(function(){
var self = this;
this.autorun(function(){
var count = Channels.find().count();
self.$('select').material_select();
});
});
my problem is to bind a model, that I istanciate at certain time during my application, to a View that has been created at initialization time. Let me explain better:
In my route I istanciate a View:
...
var view = new app.FirstView();
view.render();
In
app.FirstView = Backbone.View.extend({
initialize: function(){
...
this.SidebarView = new app.SidebarView();
}
... });
At certain time X during my application I have this behaviour in an another view:
app.AnotherView = Backbone.View.extend({
...
onClickHandler: function(){
var aModel = app.aModel();
var view = app.aView({ model: aModel });
}
})
My problem now, is to bind aModel defined in the onClickHandler to SidebarView which I created and bounded to the FirstView at initialization time.
Please tell me if something is not clear.
Thanks in advance
one solution is to use an event for example,
In your AnotherView trigger a event and pass to model to View
onClickHandler: function(){
var aModel = app.aModel();
Backbone.trigger('model:assigned',aModel);
}
in your sidebarView's initialize you should listen for event
Backbone.on("model:assigned",function(passedModel){
this.model = passedModel;
})
Note1: You must be sure that sidebarView is initialized by the time you are triggering event.
Note2: Try avoiding Global events , i used as i don't know your code structure.
i am trying to make a two way binding in Knockout.js, but i am not pretty sure, that my approach is the right suggestion.
What i need is very simple:
I need the id of the binded element of my observable.
Here is my first approach:
HTML:
<div id='test' data-bind="attr {id: 'test'}, html: id"></div>
Javascript:
var vm = {
id: ko.observable()
};
ko.applyBindings(vm);
In the end, i need the id iformation in my viewmodel.
Maybe it´s not possible and not really reliable to knockout. But i dont want to go through the domtree with jquery selector if dont have the information in my viewmodel.
Thanks in advance
You need to give id in observable
id: ko.observable('test')
this will produce id
Fiddle Demo
From the comments on the original question, I don't think you're looking for two-way binding - you're looking for a way to cache the jQuery selector so that it can be accessed in your view model.
For that, I would suggest the following:
Add properties or variables in your view model that will hold the selector results. These do not need to be observables, as the IDs of your elements will never change.
Create a function that you call once on initialization of your view model, that will assign the results of the jQuery selectors to their respective properties/variables.
Subscribe to whatever observable contains the data, and trigger your animation from there.
Here's an example of how this could be done in your view model (JSFiddle example):
var ViewModel = ( function () {
var ViewModel = function () {
// ... stuff
this.data = ko.observable( 'No data here :(' );
this.data.subscribe( this.animate.bind( this ) );
};
// This is the function where you store the result of the jQuery selectors
ViewModel.prototype.cacheSelectors = function () {
this.testElement = $( '#test' );
};
// This is an example function that will load your data
ViewModel.prototype.loadData = function () {
this.data( 'Oh wait, here\'s some data!' );
};
// This is an example function that you could trigger to animate your element
ViewModel.prototype.animate = function () {
this.testElement.animate( { 'padding-left': '+=250px' }, 'slow' );
};
return new ViewModel();
}() );
ViewModel.cacheSelectors();
ko.applyBindings( ViewModel );
I have a sortable accordion loaded with a foreach-template loop over a ko.observableArray() named "Tasks".
In the accordion I render the TaskId, the TaskName, and a task Description - all ko.observable().
TaskName and Description is rendered in input/textarea elements.
Whenever TaskName or Description is changed, an item is de-selected, or another item is clicked on, I want to call a function saveEdit(item) to send the updated TaskName and Description to the database via an ajax request.
I need to match the TaskId with the Tasks-array to fetch the actual key/value-pair to send to the saveEdit().
This is the HTML:
<div id="accordion" data-bind="jqAccordion:{},template: {name: 'task-template',foreach: Tasks,afteradd: function(elem){$(elem).trigger('valueChanged');}}"></div>
<script type="text/html" id="task-template">
<div data-bind="attr: {'id': 'Task' + TaskId}" class="group">
<h3><b><span data-bind="text: TaskId"></span>: <input name="TaskName" data-bind="value: TaskName /></b></h3>
<p>
<label for="Description" >Description:</label><textarea name="Description" data-bind="value: Description"></textarea>
</p>
</div>
</script>
This is the binding:
ko.bindingHandlers.jqAccordion = {
init: function(element, valueAccessor) {
var options = valueAccessor();
$(element).accordion(options);
$(element).bind("valueChanged",function(){
ko.bindingHandlers.jqAccordion.update(element,valueAccessor);
});
},
update: function(element,valueAccessor) {
var options = valueAccessor();
$(element).accordion('destroy').accordion(
{
// options put here....
header: "> div > h3"
, collapsible: true
, active: false
, heightStyle: "content"
})
.sortable({
axis: "y",
handle: "h3",
stop: function (event, ui) {
var items = [];
ui.item.siblings().andSelf().each(function () {
//compare data('index') and the real index
if ($(this).data('index') != $(this).index()) {
items.push(this.id);
}
});
// IE doesn't register the blur when sorting
// so trigger focusout handlers to remove .ui-state-focus
ui.item.children("h3").triggerHandler("focusout");
if (items.length) $("#sekvens3").text(items.join(','));
ui.item.parent().trigger('stop');
}
})
.on('stop', function () {
$(this).siblings().andSelf().each(function (i) {
$(this).data('index', i);
});
})
.trigger('stop');
};
};
My first thought was to place the line
$root.SelectedTask( ui.options.active );
in an .on('click') event function where SelectedTask is a ko.observable defined in my viewModel. However, the .on('click') event seems to be called a lot and it's generating a lot of traffic. Also, I can´t quite figure out where to put the save(item) call that sends the selected "item" from Tasks via an ajax-function to the database.
Any help is highly appreciated. Thanks in advance! :)
Whenever TaskName or Description is changed, an item is de-selected, or another item is clicked on, I want to call a function saveEdit(item) to send the updated TaskName and Description to the database via an ajax request.
This sounds like the core of what you want to do. Let's start out with a Task model
function Task (data) {
var self = this;
data = data || {};
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
self.description = ko.observable(data.description);
}
And then we need our View Model:
function ViewModel () {
var self = this;
self.tasks = ko.observableArray();
self.selectedTask = ko.observable();
self.saveTask = function (task) {
$.ajax({ ... });// ajax call that sends the changed data to the server
};
var taskSubscription = function (newValue) {
self.saveTask(self.selectedTask());
};
var nameSubscription, descriptionSubscription;
self.selectedTask.subscribe(function (newlySelectedTask) {
if (newlySelectedTask instanceof Task) {
nameSubscription =
newlySelectedTask.name.subscribe(taskSubscription);
descriptionSubscription =
newlySelectedTask.description.subscribe(taskSubscription);
self.saveTask(newlySelectedTask);// But why?
}
});
self.selectedTask.subscribe(function (currentlySelectedTask) {
if (currentlySelectedTask instanceof Task) {
nameSubscription.dispose();
descriptionSubscription.dispose();
self.saveTask(currentlySelectedTask);// But why?
}
}, null, 'beforeChange');
}
So what's going on here? Most of this should be pretty self explanatory so I'm just going to focus on the subscriptions. We created a taskSubscription function so we're not constantly having it defined every time the self.selectedTask changes.
We have two subscriber functions. The first fires after the selectedTask's value has changed and the second fires before it changes. In both, we verify that the new value is an instance of a Task object. In the after change subscription, we set up two subscriptions on the name and description properties. Then I capture the return value from the subscription function into two private variables. These are used in the before change function to dispose of those subscriptions so that if those Tasks are ever updated when they're not currently selected, then we don't continue to fire off the saveTask function.
I've also added self.saveTask in each of the subscriptions to the selectedTask observable. I asked why in here because, why save it if we don't know if the value has changed or not? You may be making ajax requests needlessly here.
Also, as demonstrated by this code, you can set up these subscriptions to make ajax requests every time the value changes but that may end up making a LOT of requests. A better option might be to set up functionality in your Task model that can track whether or not it is 'dirty' or not. Meaning one or more of its values have changed that requires updating.
function Task (data) {
var self = this;
// Make a copy of the data object coming in and use this to save previous values
self._data = data = $.extend(true, { id: null, name: null, description: null }, data);
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
self.description = ko.observable(data.description);
for (var prop in data) {
if (ko.isSubscribable(self[prop])) {
self[prop].subscribe(function (oldValue) {
data[prop] = oldValue;
}, null, 'beforeChange');
}
}
}
Task.prototype.isDirty = function () {
var self = this;
for (var prop in self._data) {
if (ko.isSubscribable(self[prop])) {
if (self._data[prop] !== self[prop]())
return true;
}
}
return false;
};
And of course you need a way to save it, or make it not dirty
Task.prototype.save = function () {
var self = this;
for (var prop in self._data) {
if (ko.isSubscribable(self[prop])) {
self._data[prop] = self[prop]();
}
}
};
Using the same concept you can also create Task.prototype.revert that does the opposite of what .save does. With all this in place, you could forego setting up the subscriptions on the individual name and description properties. I wanted to show that option to just demonstrate how one might want to use the .dispose method on a subscription. But now you can just subscribe to the selectedTask observable ('beforeChange') and see if the currently selected task that you're about to swap out isDirty. If it is, call the saveTask function, and when that completes, call the .save function on the Task so that it is no longer dirty.
This is probably the route I would go in implementing something like this. The beauty of it is, I haven't written a single line of code that has anything to do with the manipulating the View. You can set the selectedTask any way you see fit. What I would do is, bind the selectedTask observable to a click binding on the <h3> element inside of the accordion. That way, every time a user clicks on any of the accordions, it will potentially save the previously selected task (if any of the property values had changed).
Hopefully that addresses your scenario here of trying to save a Task when certain events are triggered.