首页 > 其他 > 详细

学习笔记 - 数据绑定之knockout

时间:2016-02-24 22:30:31      阅读:202      评论:0      收藏:0      [点我收藏+]

参考:

http://www.cnblogs.com/TomXu/archive/2011/11/21/2257154.html

http://knockoutjs.com/documentation/introduction.html

复习:AngularJS的数据绑定

显示文本

<p>{{greeting}}</p>

或者

<p ng-bind=”greeting”></p>

 

表单输入

<form ng-controller=”SomeController”>

         <input type=”checkbox” ng-model=”youCheckedIt”>

</form>

 

列表

<ul ng-controller=’StudentController’>

         <li ng-repeat=’student in students’>

                   <a href=’/student/view/{{student.id}}’>{{student.name}}</a>

         </li>

</ul>

 

表格

<table ng-controller=’AlbumController’>

         <tr ng-repeat=’track in album’>

                   <td>{{$index+1}}</td>

                   <td>{{track.name}}</td>

                   <td>{{track.duration}}</td>

         </tr>

</table>

 

使用$watch监控数据模型的变化

 

Knockout基础学习

示例代码出现错误,提示jquery-tmpl版本太旧,解决办法

http://blog.degree.no/2012/09/microsoft-jscript-error-jquery-tmpl-is-too-old/

库的在线引用地址

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript" src="./jquery.tmpl.js"></script>

<script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-latest.js"></script>

 

Jquery.tmpl.js下载自

https://raw.githubusercontent.com/BorisMoore/jquery-tmpl/master/jquery.tmpl.js

https://github.com/BorisMoore/jquery-tmpl

 

入门

重要概念:

         声明式绑定

         UI界面自动刷新

         依赖跟踪

         模板

基本使用

         启用绑定

         ko.applyBindings(viewModel)

         数据模型

         var viewModel = {

                   chosenMeal: ko.observable(availableMeals[0])

         }

         数据

         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 }

       ];            

         使用绑定,写变量

         Chosen meal: <select data-bind="options: availableMeals,

                                optionsText: ‘mealName‘,

                                value: chosenMeal"></select>

         使用绑定,读变量,并作为参数提供给函数

<p>

    You‘ve chosen:

    <b data-bind="text: chosenMeal().description"></b>

    (price: <span data-bind=‘text: formatPrice(chosenMeal().extraCost)‘></span>)

</p>

         格式化函数

function formatPrice(price) {

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

}

Observables 可观察变量

概念

observables, Dependent Observables, Observable Array

核心功能

         observables 可观察变量 Dependency tracking 依赖跟踪

         declarative bindings 显式绑定

         templating 模板

View-Model

         视图模型

激活Knockout

         ko.applyBindings(myViewModel, document.getElementById(‘someElementId‘))

可观察变量,声明

var myViewModel = {

    personName: ko.observable(‘Bob‘),

    personAge: ko.observable(123)

};

可观察变量,读写

         读:myViewModel.personAge()

         写:myViewModel.personName(‘Mary‘),支持链式语法

         绑定,data-bind,注册到可观察变量

可观察变量,显示订阅

var subscription = myViewModel.personName.subscribe(function (newValue) { /* do stuff */ });

// ...then later...

subscription.dispose(); // I no longer want notifications

 

依赖可观察变量

         var viewModel = {

             firstName: ko.observable(‘Bob‘),

             lastName: ko.observable(‘Smith‘)

};

viewModel.fullName = ko.dependentObservable(function () {

    return this.firstName() + " " + this.lastName();

}, viewModel);

 

从依赖变量写入可观察变量

viewModel.fullName = ko.dependentObservable({

 

    read: function () {

        return this.firstName() + " " + this.lastName();

    },

 

    write: function (value) {

        var lastSpacePos = value.lastIndexOf(" ");

        if (lastSpacePos > 0) { // Ignore values with no space character

            this.firstName(value.substring(0, lastSpacePos)); // Update "firstName"

            this.lastName(value.substring(lastSpacePos + 1)); // Update "lastName"

        }

    },

    owner: viewModel

});

 

 

使用依赖变量数组observable array

var myObservableArray = ko.observableArray();    // Initially an empty array

myObservableArray.push(‘Some value‘);          // Adds the value and notifies observers

 

// This observable array initially contains three objects

var anotherObservableArray = ko.observableArray([

    { name: "Bungle", type: "Bear" },

    { name: "George", type: "Hippo" },

    { name: "Zippy", type: "Unknown" }

]);

 

js等价读取信息:length, indexOf, slice

js数组等价操作:pop, push, shift, unshift, reverse, sort, splice

特殊操作:remove, removeAll

绑定语法一

         visible: 绑定到DOM元素,控制元素是否显示

         text: 控制元素的文本值

         html: 控制元素显示的HTML值

         css: 添加或删除一个或多个CSS class到DOM元素上

         style: 添加或删除一个或多个DOM元素上的style值

         attr: 提供了一种方式可以设置DOM元素的任何属性值

绑定语法二

         click

         event, 例如keypress, mouseover, mouseout

         submit

         enable

         disable

绑定语法三

         value, <input>, <select>, <textarea>

         checked, <input type=’checkbox’>, <input type=’radio’>

         options, <select>, <select size=’6’>

         selectedOptions, multi-select

         uniqueName

 

模板绑定

         jquery.tmpl

你可以使用任何你模板引擎支持的语法。jquery.tmpl执行如下语法:

    ${ someValue } — 参考文档

    {{html someValue}} — 参考文档

    {{if someCondition}} — 参考文档

    {{else someCondition}} — 参考文档

{{each someArray}} — 参考文档

 

创建自定义绑定

ko.bindingHandlers.yourBindingName = {

    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {

        // This will be called when the binding is first applied to an element

        // Set up any initial state, event handlers, etc. here

    },

 

    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {

        // This will be called once when the binding is first applied to an element,

        // and again whenever the associated observable changes value.

        // Update the DOM element based on the supplied values here.

    }

};

 

加载或保存JSON数据

加载或保存数据:例如使用jQuery的$.getJSON, $.post, $.ajax

转化ViewModel数据到JSON格式,有时需要json2.js类库

         ko.toJS 转化为JS对象

         ko.toJSON 转化为JSON字符串

使用JSON更新ViewModel数据

         手动方式

 

或者使用 knockout.mapping

使用Mapping插件

         var viewModel = ko.mapping.fromJS(data); //创建ViewModel

         ko.mapping.fromJS(data, viewModel); //更新ViewModel

用法:

         key, create, update, ignore, include, copy

两种方式创建viewModel

 

 

应用举例

常用的控件

 

学习笔记 - 数据绑定之knockout

原文:http://www.cnblogs.com/gibbonnet/p/learningknockout.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!