Ember 2.1.0
我正在使用 FitText举个例子,但我的问题是针对任何 jQuery 插件/或实际上 - 任何 JS 插件。
有时我想在站点范围内使用一些东西。假设我计划在整个 Ember 应用程序的任何地方使用一个省略号或孤立的文本脚本。
然后有时会有诸如 FitText 插件之类的东西,我想在这里或那里用页面标题做一些事情。
然后想象一下在 index.hbs 上或仅在进入第一条路线时有一些加载动画或其他东西 - 一次性。
ember-cli-build.js (以前的 Brocfile.js)
...
app.import('vendor/jquery.fittext.js');
...
模板/index.hbs
<div class='example-div'>
<h1 class='example-target'>Some <span>type</span>.</h1>
</div>
标准执行
$('.example-target).fitText(1.2, { minFontSize: '20px', maxFontSize: '40px' });
我如何在每种情况下实现它?
我的第一次尝试只是在 app.js
中达到顶层——我确信这并不理想——但我会坚持到我可以升级。
例如,我目前有这个功能:
应用程序.js
...
function randomLandingClass() {
var themes = ['color-theme', 'highlight-theme', 'alternate-theme'];
var randomTheme = themes[Math.floor(themes.length * Math.random())];
$('body').addClass(randomTheme);
}
Ember.MODEL_FACTORY_INJECTIONS = true;
App = Ember.Application.extend({
modulePrefix: config.modulePrefix,
podModulePrefix: config.podModulePrefix,
Resolver,
ready() {
randomLandingClass();
$('.example-target').fitText(1.2, { minFontSize: '20px', maxFontSize: '40px' });
}
});
...
randomLandingClass 按预期运行并使用 jQuery,但 fitText 方法没有。
我已经成功地使用这个特定插件构建了一个组件,但这只是忽略了我的误解。
如果我想在站点范围内使用一个方法,应该在哪里调用它?
如果我只想在几个不同的路由中使用一个方法,应该如何调用它?
如果我想使用一次,应该在哪里/如何调用它?
我试过很多路由钩子(Hook)都无济于事。
我缺少的核心概念是什么?
最佳答案
不确定你的意思 * 但那只是忽略了我的误解。” - 组件是 Ember 的方式来做到这一点,并在 Ember 结构中隐藏/包装 jQuery 插件功能。
// components/fit-text.js
export default Ember.Component.extend({
// defaults for the parameters
scale: 1.2,
minFontSize: '20px',
maxFontSize: '40px',
initialize: function() {
this.$().fitText(
this.get('scale'), {
minFontSize: this.get('minFontSize'),
maxFontSize: this.get('maxFontSize')
}
);
}.on('didInitAttrs', 'didUpdateAttrs');
});
现在您可以在模板中像这样使用它了:
<div class='example-div'>
{{#fit-text tagName='h1' class='example-target'}}Some <span>type</span>.{{/fit-text}}
</div>
如果你愿意,你可以覆盖默认参数,例如
<div class='example-div'>
{{#fit-text tagName='h1' class='example-target' scale=1.5 maxFontSize='50px'}}Some <span>type</span>.{{/fit-text}}
</div>
关于javascript - 在 Ember 应用程序中的何处使用 jQuery 插件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33311165/