Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of Knockout application development

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the knowledge points of Knockout application development". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1 introduction to Knockout (Introduction)

Knockout is a lightweight UI class library that simplifies the JavaScript front-end UI by applying the MVVM pattern.

Knockout has the following four important concepts:

◆ declarative binding (Declarative Bindings): it is easy to associate model (model) data to DOM elements using concise and readable syntax.

◆ UI interface automatic refresh (Automatic UI Refresh): when your model state (model state) changes, your UI interface will be updated automatically.

◆ dependency tracking (Dependency Tracking): to transform and federate data, implicitly establish relationships between your model data.

◆ templates (Templating): quickly write complex nested UI for your model data.

Abbreviation: KO

Official website: http://knockoutjs.com

2 getting started (Getting started)

2.1 how KO works and its benefits

Knockout is a data model-based JavaScript class library that helps you create rich text, responsive display and editing user interfaces. Any time your UI needs to be updated automatically (for example, updates depend on user behavior or changes in external data sources), KO can be easily implemented for you and easy to maintain.

Important features:

◆ gracefully relies on tracking-whenever your data model is updated, it will automatically update the corresponding content.

◆ declarative binding-an easy-to-understand way to associate specified parts of your user interface with your data model.

◆ flexible and comprehensive templates-use nested templates to build complex dynamic interfaces.

◆ is easily extensible-custom behaviors can be implemented as new declarative bindings in a few lines of code.

Additional benefits:

◆ pure JavaScript class library-compatible with any server-side and client-side technology

◆ can be added to the top of the Web program-no major architectural changes are required

◆ succinct-Gzip before about 25kb

◆ is compatible with any major browser (IE 6 +, Firefox 2 +, Chrome, Safari, others)

◆ Comprehensive suite of specifications (behavior-driven development)-means that it can be easily verified on new browsers and platforms.

Developers who have used Silverlight or WPF may know that KO is an example of the MVVM pattern. If you are familiar with Ruby on Rails or other MVC technologies, you may find that it is a MVC real-time form with declarative syntax. In other words, you can think of KO as a way to create a UI user interface by editing JSON data. No matter what it does for you,

OK, how to use it?

To put it simply: declare your data as a JavaScript model object (model object) and bind DOM elements or templates (templates) to it.

Let's look at an example.

Think of a page where air travelers can upgrade premium food packages for their travel, and when they choose a package, the page immediately displays a description and price of the package. First, declare the available packages:

Var availableMeals = [{mealName: 'Standard', description:' Dry crusts of bread', extraCost: 0}, {mealName: 'Premium', description:' Fresh bread with cheese', extraCost: 9.95}, {mealName: 'Deluxe', description:' Caviar and vintage Dr Pepper', extraCost: 18.50}]

If you want these three options to be displayed on the page, we can bind a drop-down menu (for example: element) to this data. For example:

Meal upgrades

Make your flight more bearable by selecting a meal to match your social and economic status.

Chosen meal:

To enable Knockout and make your binding effective, add the following code after the availableMeals variable declaration:

Var viewModel = {/ * we'll populate this in a moment * /}; ko.applyBindings (viewModel); / / Makes Knockout get to work / / Note: ko. ApplyBindings needs to be applied after the above HTML to be effective.

You can learn more about view model and MVVM in this series. Now your page will look like this render:

Response selection

Next, declare a simple data model to describe the package that the traveler has chosen, and add an attribute to the current view model:

Var viewModel = {chosenMeal: ko.observable (availableMeals [0])}

What is ko.observable? It is a basic concept in KO. UI can observe its value and respond to its changes. Here we set chosenMeal as UI to monitor the selected package and initialize it, using the * values in availableMeal as its default value (for example: Standard).

Let's associate chosenMeal to the drop-down menu, simply update the element and tell it to have the value of the element read / write to the model property chosenMeal:

Chosen meal:

Theoretically, we can now read / write the chosenMeal attribute, but we don't know what it does. Let's show the description and price of the selected package:

You've chosen: (price:)

Therefore, the package information and price will be automatically updated according to the user's choice of different package items:

More about the use of observables and dependency tracking

One thing: if only the price could be formatted with a currency symbol, it would be possible to declare a JavaScript function.

Function formatPrice (price) {return price = = 0? "Free": "$" + price.toFixed (2);}

... Then update the binding information and use this function.

(price:)

... The result of the interface display will be much better:

Price formatting shows that you can write any JavaScript code in your binding, and KO can still detect your binding dependency code. This shows how KO does only partial updates without re-render the entire page when your model changes-just the part where the dependent value changes.

Chained observables is also supported (for example, total price depends on price and quantity). When the chain changes, the downstream part of the dependency will be re-executed, and all relevant UI will be updated automatically. There is no need to declare associations between observables; the KO framework executes automatically at run time.

You can get more information from observables and observable arrays. The above example is very simple and does not cover a lot of KO features. You can get more embedded bindings and template bindings.

Are KO and jQuery (or Prototype, etc.) competitive or can they be used together?

Everybody loves jQuery! It is a framework for manipulating elements and events on the page, excellent and easy to use, and be sure to use jQuery,KO to solve different problems in DOM operations.

If the page requirements are complex, it takes more code to just use jQuery. For example, a list is displayed in a table, and then the number of lists is counted. The Add button is enabled when the data row TR is less than 5 tones, otherwise it is disabled. JQuery has no basic concept of a data model, so you need to get the amount of data (from table/div or specially defined CSS class). If you need to display the amount of data in some SPAN, you should also remember to update the text of this SPAN when adding new data. Of course, you also need to judge that the Add button is disabled when the total is > = 5. Then, if you want to implement the Delete function, you have to point out which DOM element needs to be changed after it is clicked.

How is the implementation of Knockout different?

Using KO is very simple. Depict your data as a JavaScript array object myItems, and then use a template to convert the array into a table (or a set of DIV). Whenever the array changes, the UI interface responds to the change (without indicating how or where to insert a new row), and all that's left is to synchronize. For example, you can declare that you can bind the following SPAN to display the amount of data (it can be placed anywhere on the page, not necessarily in template):

There are items

That will be all! You don't need to write code to update it, its update depends on the change of the array myItems. Similarly, the enabling and disabling of the Add button depends on the length of the array myItems, as follows:

Add

After that, if you want to implement the Delete function, you don't have to point out how to manipulate the UI element, just modify the data model.

Summary: KO does not compete with jQuery or similar DOM-operated API. KO provides advanced features for associating data models and user interfaces. KO itself does not rely on jQuery, but you can use jQuery at the same time, and vivid and smooth UI changes require the real use of jQuery.

2.2 download and install

The core class library of Knockout is pure JavaScript code and does not rely on any third-party class libraries. So follow these steps to add KO to your project:

Download the * * version of the Knockout class library. For official development and product use, please use the default compressed version (knockout-x.x.js).

Debug debugging purposes, you can use the uncompressed version (knockout-x.x.debug.js). It has the same functionality as the compressed version, but has readable source code with full variable names and comments, and does not hide the internal API.

Use tags to reference Knockout class library files in your HTML page.

That's all you need.

Open template binding

... Unless you want to use the template binding feature (you are likely to use it because it is very useful), you need to reference two more JavaScript files. The default template engine for KO is jquery.tmpl.js, which relies on jQuery. So you need to download the following two files and reference them before referencing KO:

JQuery 1.4.2 or later

Jquery-tmpl.js-this version is easy to use, or you can visit the official website to find the * version.

Correct citation order:

(of course, you need to update the above file path and file name according to your file path. )

This is the end of the content of "what are the knowledge points of Knockout application development". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report