在 Riot Js 中是否可以将 javascript 代码与标记文件分开?
Is it possible to separate the javascript code from the tag file in Riot Js?
我想知道是否可以这样做:
<todo>
<div class="greetings">Hello, world!</div>
<script src="/path/to/my/file.js"></script>
</todo>
标签将保留视图 (html) 而 js 代码保留在不同的文件中:
- todo.tag (html/css)
- todo.js
在研究之后,我发现可以使用 mixins 将 js 从标签文件中分离出来。所以,我们会有这样的东西:
<dropdown>
<select>...</select>
<!-- more html code here -->
this.mixin(Dropdown);
</dropdown>
Dropdown 实例将在 dropdown.js 中,标签将在 dropdown.tag 中。
希望这对您有所帮助。
为了提供 mixin
解决方案的替代方案,这里是另一种将标记与逻辑分开的方法。
看看this Plunker(我的一个同事写的)。关键部分是您引用标记函数的方式。 <script>todoTag.call(this, this.opts);</script>
。在这种情况下,todoTag
是一个全局函数。但是没有什么能阻止您使用命名空间功能或使用某种形式的模块加载。
来自 plunker:
todo.tag.html:
<todo>
<!-- your markup -->
<script>todoTag.call(this, this.opts);</script>
</todo>
todo.tag.js:
function todoTag(opts) {
// your logic
}
我找到了另一种方法,通过使用常规的 js 构造函数将 js 代码与标签分开,如下所示:
<dropdown>
<!-- html code -->
<script>new Dropdown(this)</script>
</dropdown>
那我们就可以
function Dropdown(tag) {
// constructor code
}
和
Dropdown.prototype = { ... }
一如既往
我想知道是否可以这样做:
<todo>
<div class="greetings">Hello, world!</div>
<script src="/path/to/my/file.js"></script>
</todo>
标签将保留视图 (html) 而 js 代码保留在不同的文件中:
- todo.tag (html/css)
- todo.js
在研究之后,我发现可以使用 mixins 将 js 从标签文件中分离出来。所以,我们会有这样的东西:
<dropdown>
<select>...</select>
<!-- more html code here -->
this.mixin(Dropdown);
</dropdown>
Dropdown 实例将在 dropdown.js 中,标签将在 dropdown.tag 中。
希望这对您有所帮助。
为了提供 mixin
解决方案的替代方案,这里是另一种将标记与逻辑分开的方法。
看看this Plunker(我的一个同事写的)。关键部分是您引用标记函数的方式。 <script>todoTag.call(this, this.opts);</script>
。在这种情况下,todoTag
是一个全局函数。但是没有什么能阻止您使用命名空间功能或使用某种形式的模块加载。
来自 plunker:
todo.tag.html:
<todo>
<!-- your markup -->
<script>todoTag.call(this, this.opts);</script>
</todo>
todo.tag.js:
function todoTag(opts) {
// your logic
}
我找到了另一种方法,通过使用常规的 js 构造函数将 js 代码与标签分开,如下所示:
<dropdown>
<!-- html code -->
<script>new Dropdown(this)</script>
</dropdown>
那我们就可以
function Dropdown(tag) {
// constructor code
}
和
Dropdown.prototype = { ... }
一如既往