-1

I have developed many applications with javascript and knockout.js but this time I am so much confused now. As we all know that Knockout is works on MVVM pattern (i.e dual binding). Lets take a example for my confusion: I have a viewModel:

var myViewModel = {
    firstName: ko.observable('Bob'),
    lastName: ko.observable('dev')
};

ko.applyBindings(new myViewModel());

and I have bound the above viewModel to two text boxes like:

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

<p>First name:</p><input type="text" data-bind="value: firstName" />
<p>Last name:</p><input type="text" data-bind="value: lastName " />

Now this sample observable code works for me. When I change the values from script or in the input boxes, they will be bound.

Now I want to do this same task with only basic javascript. How can I do this? Any help will be appreciated.

kix
  • 3,290
  • 27
  • 39
  • 1
    How can you change the value using javascript? myViewModel.firstName("newvalue") – Steen Tøttrup Aug 26 '14 at 12:34
  • Are you asking how to remove the dependency on knockout and do all of this in vanilla javascript? – xdumaine Aug 26 '14 at 12:35
  • Check this link: http://stackoverflow.com/questions/16483560/how-to-implement-dom-data-binding-in-javascript – Jaime García Pérez Aug 26 '14 at 12:45
  • 2
    Take a look at the source code of Knockout! Seriously, it is not that complex. Start looking at the observable wrapper itself, it is pretty straight-forward. Combine this with event listeners, and you are already pretty far. However, soon you will need more, and start implementing it. Ultimately, you might find using Knockout is a better approach, cause they do the work for you. They test it, they get feedback, and they do a good job at keeping Knockout's core very lean and mean. – Hans Roerdinkholder Aug 26 '14 at 12:56

2 Answers2

0

You can make simple version with javascript events. You can listen to onchange or onkeyup event on input and update value elsewhere via callback for this event. If you want also javascript object for some sort of model and update it, you can create custom events and produce them on property change in model.

sepulchered
  • 814
  • 7
  • 18
0

Object.observe for the win. It's gonna be included in ECMA6 standard.

Demo code snippet -

//Datasource which you want to observe
var dataSource = {};

// Which we then observe
Object.observe(datasource, function(changes){

    // Async Callback
    newValue.forEach(function(change) {
        console.log(change.type, change.name, change.oldValue);
    });

});

This is how we can observe any property/ variable using core JavaScript.

Detailed and beautiful article here : http://www.html5rocks.com/en/tutorials/es7/observe/

Rahul Patil
  • 5,656
  • 6
  • 37
  • 65