Creating custom bindings
You’re not limited to using the built-in bindings like click, value, and so on — you can create your own ones. This is how to control how observables interact with DOM elements, and gives you a lot of flexibility to encapsulate sophisticated behaviors in an easy-to-reuse way.
从官网的解释来看,就是安照你项目中的特殊需求,去封装一种简单的可以复用的高级行为,它用来控制被观察的对象与DOM元素的交互。
举个简单的例子
<!DOCTYPE html>
<html><head>
<title>
Data Binding with KnockoutJS</title>
</head>
<body>
<form>
<textarea
data-bind=
"tinymce: htmlText"
></textarea>
</form>
<button
type=
"button"
data-bind=
"click: resetContent"
>
Reset content</button>
<h2>
Preview</h2>
<div
data-bind=
"html: htmlText"
></div>
<script
type=
'text/javascript'
src=
'js/jquery.js'
></script>
<script
type=
'text/javascript'
src=
'js/tinymce/jquery.tinymce.min.js'
></script>
<script
type=
'text/javascript'
src=
'js/tinymce/tinymce.min.js'
></script>
<script
type=
'text/javascript'
src=
'js/knockout-3.2.0.js'
></script>
<script
type=
'text/javascript'
src=
'js/kobinding.js'
></script>
<script>
function
ViewModel
()
{
var
self
=
this
;
self
.
htmlText
=
ko
.
observable
();
self
.
resetContent
=
function
()
{
self
.
htmlText
(
''
);
};
};
var
viewModel
=
new
ViewModel
();
ko
.
applyBindings
(
viewModel
);
</script>
</body>
</html>
kobinding.js
ko
.
bindingHandlers
.
tinymce
=
{
init
:
function
(
element
,
valueAccessor
,
allBindingsAccessor
)
{
var
tinymceOptions
=
{
setup
:
function
(
editor
)
{
editor
.
on
(
'change'
,
function
(
event
)
{
valueAccessor
()(
event
.
target
.
getContent
());
});
}
};
$
(
element
).
text
(
valueAccessor
()()
);
setTimeout
(
function
()
{
$
(
element
).
tinymce
(
tinymceOptions
);
},
0
);
ko
.
utils
[
'domNodeDisposal'
].
addDisposeCallback
(
element
,
function
()
{
$
(
element
).
tinymce
().
remove
();
});
},
'update'
:
function
(
element
,
valueAccessor
,
allBindings
)
{
var
tinymce
=
$
(
element
).
tinymce
(),
value
=
valueAccessor
()();
if
(
tinymce
)
{
if
(
tinymce
.
getContent
()
!==
value
)
{
tinymce
.
setContent
(
value
);
}
}
}
};
这里init属性是在当viewmodel绑定上knockout时,在第一次初始化时,会建立TinyMCE options和绑定textarea到TinyMCE。
在TinyMCE的构建中,通过TinyMCE options的setup方法建立一个对于TinyMCE变化的监听。每当TinyMCE触发chang事件,编辑的内容都会发生相应变化。
update顾名思义,就是被观察对象发生改变时会触发
这里需要说明一点的是
valueAccessor
()()
第一个valueAccessor
()代表
htmlText,这个属性值第二个valueAccessor
()()代表被执行访问的当前观察对象的值