Knockoutjs 3.X API chapter II Data Monitoring (1) View model and monitoring

Source: Internet
Author: User

Data Monitoring

Ko's three built-in core features:

    1. monitoring ( observable dependency tracking )
    2. Declaration bindings ( Span style= "COLOR: #222222" >declarative bindings "
    3. template ( templating )

On this page, you will learn the first of three core features. But before we do, let's look at the concept of the MVVM pattern and The concept of the view model .

MVVM pattern and view model

Model-View-view model (MVVM) is the design pattern used to build the user interface. It describes how to split a complex UI into three parts:

    • model : Data stored by the application. This data represents your business domain objects and operations (for example, bank accounts that can make money transfers) and is independent of any user interface. When using KO, it is common to call some server-side APIs with Ajax to read and write data to this storage model.
    • view model : It can be understood as a representation of data presentation on the UI and data staging after operation. For example, if you look at a list, the view model presents a series of data and exposes methods for related actions (adding and deleting items).

      It is important to note that The view model does not participate in how the UI is rendered: it does not have any concept of a button or display style. is not a persisted data model, which is data that the user is viewing or not saving. When using KO, your view model is a pure JavaScript object.

    • view : Represents the visible part of the MVVM mode state. User's interactive interface. It displays information from the view model, sends commands to the view model (for example, when the user taps the button).

      when using KO, A view is a simple way to declare an HTML document that is bound to its view model. Alternatively, you can use the data from the view model to generate an HTML template.

To create a model with a KO view, simply declare any JavaScript object. For example:

    1. var myviewmodel = {
    2. ???? PersonName: ' Bob ',
    3. ???? Personage:123
    4. };

Then, you can create a very simple view using the claim binding concept model. For example, the following markup shows the PersonName value:

    1. The name is <spandata-bind= "Text:personname" ></span>
activating KO's binding relationship

The Data-bind property is not part of the underlying element property of HTML, but it can still work correctly. But since the browser does not know what this means, you need to activate the KO's binding relationship to make it effective.

To activate the KO's binding relationship, add a line of code to the <script> module:

    1. Ko.applybindings (Myviewmodel);

You can write the script at the bottom of the HTML document, or you can write it at the top of the HTML document and process it after the DOM is ready for the document, such as using jquery's $ function.

It's all right! Your view will now show the following HTML written:

    1. The name is <span>Bob</span>

Parameters of the Ko.applybindings

The first parameter is to have a high number of KO, the view model you want to bind is that.

The second parameter that you can pass is the Data-bind property that defines the part of the document to search for. For example, Ko.applybindings (Myviewmodel, document.getElementById (' Someelementid ')). This restriction activates the scope of the bound view model in the HTML element's ID element as Someelementid and its child elements, which is useful if you want to have multiple view model activation bindings or model bindings for different areas of each page.

Monitoring (Observable)

OK, you've seen how to create a basic view model and how to display the properties of a binding. But the main benefit of Ko is that it automatically updates your UI based on changes in the view model. How does Ko know when a part of your view model has changed? The answer is that you need to set up observable (monitoring) for your view model, which is a special JavaScript object that notifies the user of the change and can automatically detect dependencies.

For example, overwrite the previous view model object as follows:

    1. var myviewmodel = {
    2. ???? PersonName:ko.observable (' Bob '),
    3. ???? PersonAge:ko.observable (123)
    4. };

When the view model property value changes, the binding properties of the Data-bind in the UI are automatically updated. Similarly, the binding properties in the UI are automatically synchronized to the view model when they are changed.

read/write monitoring properties

?

  • To read the current value of a monitoring property, simply call the parameterless method of the view model property. In this example,myviewmodel.personname () returns ' Bob ', andmyviewmodel.personage () returns 123.
  • In order to assign a new value to a monitoring property, you only need to invoke the parameter method of the view model property and pass the value as a parameter. For example, calling Myviewmodel.personname (' Mary ') will change the name value ' Mary '.
  • You can use chained syntax to write values to model objects that have multiple monitoring properties . For example,myviewmodel.personname (' Mary '). Personage will change the name value and age value to ' Mary '? -

?

Ko will be able to monitor the monitoring properties, and when you write data-bind= "Text:personname", the text is notified PersonName changes when registering with itself.

When you change the name value of ' Mary ' when you call Myviewmodel.personname (' Mary '), the text binding automatically updates the textual content of the associated DOM element.

Statement Monitoring

You usually need to set up a subscription manually, so beginners should skip this section.

For advanced users, you can call the Subscribe function if you want to register change monitoring of your subscription notifications . For example:

    1. MyViewModel.personName.subscribe (function(newvalue) {
    2. ???? Alert ("The person'snew name is" + newvalue);
    3. });

The subscribe function is the KO intrinsic function. Most of the time, you don't need to use this because the built-in bindings and templating system management monitoring is enough.

The Subscribe function accepts three parameters: callback is the callback function that defines the value of this whenever a notification is called, and the event (optional, default "change") is the name of the notification that the events are received.

You can also terminate a subscription, and you can call the Dispose function, for example:

    1. var subscription = MyViewModel.personName.subscribe (function(newvalue) {/ * do stuff * /});
    2. ... then later ...
    3. Subscription.dispose (); //I no longer want notifications

If you want to perform the business before monitoring occurs, you can use the BeforeChange event. For example:

    1. MyViewModel.personName.subscribe (function(oldValue) {
    2. ???? Alert ("The person' s previous name is" + oldValue);
    3. }, null, "beforechange");
Force monitoring properties to notify users in real time

When assigning a value that contains the original value (a number, String, Boolean, or null), monitor the property, using the built-in notified?to ensure that the user of an observation monitoring property is always notified, even if the value is the same.

    1. MyViewModel.personName.extend ({notify: ' Always '});
delay and/or suppress change notifications

Typically, a change in the value of a monitoring property notifies its users immediately. However, if a monitoring attribute is frequently updated with high data transfer costs, you can achieve better performance by limiting or delaying change notifications. This is achieved by using the Ratelimit increment:

    1. Ensure it notifies about changes no more than once per 50-millisecond period
    2. MyViewModel.personName.extend ({ratelimit:50});

?

    1. Thank you for reading. Like, useful please eldest brother and sister-in-mercy "recommend" it! Your spiritual support is a powerful writing power for bloggers. Welcome Reprint!
    2. ?
    3. My blog: http://www.cnblogs.com/smallprogram/

?

Knockoutjs 3.X API chapter II Data Monitoring (1) View model and monitoring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.