问题

对于一般数据结构:

1、 对于基本类型的数据的变更的可观察性(observable), 可以使用  ko.observable(xxx) 来声明一个 observable对象,

  或将其绑定到视图,

  或将其绑定到其它 ko.computed 或者 ko.pureComputed 对象中;

  或者使用subscribe单独订阅其变化。

2、 对于数组型号数据结构, ko提供 ko.observableArray(xxx), 将数组做成一个可观察对象, 并开放一些类似数组的 方法,

  使用这些方法, 一旦数组发生变化, 则观察者能够被通知到。

pop, push, shift, unshift, reverse, sort, splice

All of these functions are equivalent to running the native JavaScript array functions on the underlying array, and then notifying listeners about the change:

  • push( value ) — Adds a new item to the end of array.
  • pop() — Removes the last value from the array and returns it.
  • unshift( value ) — Inserts a new item at the beginning of the array.
  • shift() — Removes the first value from the array and returns it.
  • reverse() — Reverses the order of the array and returns the observableArray (not the underlying array).
  • sort() — Sorts the array contents and returns the observableArray. The default sort is alphabetical, but you can optionally pass a function to control how the array should be sorted. See the example under sorted below.
  • splice() — Removes and returns a given number of elements starting from a given index. For example, myObservableArray.splice(1, 3) removes three elements starting from index position 1 (i.e., the 2nd, 3rd, and 4th elements) and returns them as an array.

replace, remove and removeAll

observableArray adds some more useful methods that aren’t found on JavaScript arrays by default:

  • replace( oldItem, newItem ) — Replaces the first value that equals oldItem with newItem.
  • remove( someItem ) — Removes all values that equal someItem and returns them as an array.
  • remove( function (item) { return item.age < 18; } ) — Removes all values whose age property is less than 18, and returns them as an array.
  • removeAll( ['Chad', 132, undefined] ) — Removes all values that equal 'Chad', 123, or undefined and returns them as an array.
  • removeAll() — Removes all values and returns them as an array.

问题来了, 我们的经常使用的 json数据结构, 类似restful等接口提供的数据, 如何观测其变化, 并通知到观察者?

KO.MAPPING

https://knockoutjs.com/documentation/plugins-mapping.html

使用ko,mapping插件, 可以将json对象, 转换一个嵌套的元素级别的可观察对象。

例如:

-------------------------------------

[

1, 2, 3

]

这个跟 ko.observableArray功能一致。

------------------------------------

[

{

  "a": 1

}

]

除了最外层的数组,被转换为 ko.observableArray外, 内部嵌套 "a"的属性值,也被转换为一个 ko.observable对象。

Example: Using ko.mapping

To create a view model via the mapping plugin, replace the creation of viewModel in the code above with the ko.mapping.fromJS function:

var viewModel = ko.mapping.fromJS(data);

This automatically creates observable properties for each of the properties on data. Then, every time you receive new data from the server, you can update all the properties on viewModel in one step by calling the ko.mapping.fromJS function again:

// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);

但是整个 {} 本身是没有被转换为 ko.observable 对象。

下面给给出一个简单方法

对整个{}对象观察

ko.observable

https://knockoutjs.com/documentation/observables.html

var json = {"a": 1}

var obser = ko.observable(json);

var kobser = ko.computed(function(){

  return obser()["a"] + 1;

})

// 这样一改变后, kobser也会跟着变化。

obser({"a": 2})

Writable computed observables

https://knockoutjs.com/documentation/computed-writable.html

为json对象定义到一个 ko.computed对象, 使用read方法负责读, 使用write负责写。 本质上与ko.observable方法相同,有特殊逻辑处理的时候, 才用这个方法。

function MyViewModel() {
    this.firstName = ko.observable('Planet');
    this.lastName = ko.observable('Earth');
 
    this.fullName = ko.pureComputed({
        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: this
    });
}
 
ko.applyBindings(new MyViewModel());

knockout-store

https://github.com/Spreetail/knockout-store

knockoutjs复杂对象的可观察性的更多相关文章

  1. MVVM架构~Knockoutjs系列之对象与对象组合

    返回目录 在面向对象的程序设计里,对象是核心,一切皆为对象,对象与对象之间的关系可以表现为继承和组合,而在Knockoutjs或者JS里,也存在着对象的概念,今天主要说一下JS里的对象及对象的组合. ...

  2. MVVM架构~knockoutjs系列之Mapping插件为对象添加ko属性

    返回目录 对于一个JS对象来说,如果希望将所有属性进行监视,在之前我们需要一个个对属性添加ko.observable方法,而有了Mapping插件后,它可以帮助我们这件事. 在Mapping出现之前 ...

  3. MVVM架构~knockoutjs系列之为Ajax传递Ko数组对象

    返回目录 一些要说的 这是一个很有意思的题目,在KO里,有对象和数组对象两种,但这两种对象对外表现都是一个function,如果希望得到他的值,需要进行函数式调用,如ko_a(),它的结果为一个具体值 ...

  4. 翻译:使用 ASP.NET MVC 4, EF, Knockoutjs and Bootstrap 设计和开发站点 - 6 - 业务逻辑

    Part 3: 设计逻辑层:核心开发 如前所述,我们的解决方案如下所示: 下面我们讨论整个应用的结构,根据应用中不同组件的逻辑相关性,分离到不同的层中,层与层之间的通讯通过或者不通过限制.分层属于架构 ...

  5. knockoutjs如何动态加载外部的file作为component中的template数据源

    玩过knockoutjs的都知道,有一个强大的功能叫做component,而这个component有个牛逼的地方就是拥有自己的viewmodel和template, 比如下面这样: ko.compon ...

  6. JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(一)

    前言:出于某种原因,需要学习下Knockout.js,这个组件很早前听说过,但一直没尝试使用,这两天学习了下,觉得它真心不错,双向绑定的机制简直太爽了.今天打算结合bootstrapTable和Kno ...

  7. KnockoutJS 3.X API 第八章 映射(mapping)插件

    Knockout旨在允许您将任意JavaScript对象用作视图模型. 只要一些视图模型的属性是observables,您可以使用KO将它们绑定到您的UI,并且UI将在可观察属性更改时自动更新. 大多 ...

  8. KnockoutJS 3.X API 第六章 组件(5) 高级应用组件加载器

    无论何时使用组件绑定或自定义元素注入组件,Knockout都将使用一个或多个组件装载器获取该组件的模板和视图模型. 组件加载器的任务是异步提供任何给定组件名称的模板/视图模型对. 本节目录 默认组件加 ...

  9. knockoutJS学习笔记01:从拼接字符串到编写模板引擎

    开篇 关于knockout的文章,园里已经有很多大神写过了,而且都写得很好.其实knockout学习起来还是很容易的,看看官网的demo和园里的文章,练习练习就可以上手了(仅限使用,不包含研究源码). ...

随机推荐

  1. C# 虚拟串口通信

    将主端口COM8拆分成 COM1和COM2两个虚拟端口 COM8接收的消息会传递给COM1和COM2 SerialPort spSend;//spSend,spReceive用虚拟串口连接,它们之间可 ...

  2. eslint 代码缩进 报错及解决

    一.背景 使用vue在VScode中正常写的代码,报了一堆的错误,仔细检查,发现都是缩进要么多了要么少了,总之是代码不规范的的报错. 二.原因 百度查了发现代码规范默认缩进2个空格,而VScode默认 ...

  3. js坚持不懈之12:var b = {a:1};

    今天看到一篇博客,在声明一个变量的时候用了如下格式的语法: var b = {a:1}; 不明白,百度一下.作如下解释: var: 声明一个变量 b: 表示变量的名称 =: 赋值符号 {}: 表示一个 ...

  4. Win7删除右键菜单中“图形属性”和“图形选项”

    完win7操作系统后,打完驱动在桌面右键会出现如下两个选项,平时没啥用又占用空间,那么如何删掉这两个选项呢? 操作步骤: 1.在运行中输入 regedit 确定打开注册表: 2.依次单击展开HKEY_ ...

  5. 使用.Net Core Mvc +SqlSugar +Autofac+AutoMapper+....

    开源地址:https://github.com/AjuPrince/Aju.Carefree 目前用到了 SqlSugar.Dapper.Autofac.AutoMapper.Swagger.Redi ...

  6. Python发送邮件脚本

    import smtplib from email.mime.text import MIMEText mailserver = "smtp.163.com" username_s ...

  7. (三)jdk8学习心得之方法引用

    三.方法引用 https://www.jianshu.com/p/c9790ba76cee 这边博客写的很好,可以首先阅读,在这里感谢这篇文章的博主. 1. 格式 调用者::调用者具备的方法名 2. ...

  8. LR socket协议脚本

    socket协议分为TCP.UDP两种(区别与联系在此不做赘述),一种为长连接.一种为短连接.如果创建连接时在init中对应关闭连接在end中,则为长连接:如果创建关闭连接都是在action则为短连接 ...

  9. Kafka简介及使用PHP处理Kafka消息

    Kafka简介及使用PHP处理Kafka消息 Kafka 是一种高吞吐的分布式消息系统,能够替代传统的消息队列用于解耦合数据处理,缓存未处理消息等,同时具有更高的吞吐率,支持分区.多副本.冗余,因此被 ...

  10. windows常用快捷键和指令

    快捷键: Ctrl+鼠标滚轮:更改图标大小(桌面).缩放(开始屏幕) Ctrl+A:选择所有 Ctrl+C:复制 Ctrl+E:选择搜索框(资源管理器) Ctrl+N:新窗口(资源管理器) Ctrl+ ...