通过willTransition防止转换(Preventing Transitions Via willTransition)
优质
小牛编辑
129浏览
2023-12-01
当您使用{{link-to}}帮助程序或transitionTo方法重新尝试转换时,它会触发当前活动路径上的willTransition操作。
语法 (Syntax)
Ember.Route.extend ({
actions: {
willTransition(transition) {
//handle the transition
}
}
});
例子 (Example)
下面给出的示例描述了通过活动路径上的willTransition操作防止转换。 创建一个名为willtransition的路由,并使用以下代码打开router.js文件以定义URL映射 -
import Ember from 'ember';
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config
//The const declares read only variable
const Router = Ember.Router.extend ({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('willtransition');
});
//It specifies Router variable available to other parts of the app
export default Router;
创建application.hbs文件并添加以下代码 -
//link-to is a handlebar helper used for creating links
{{link-to 'Click For Transition' 'willtransition'}}
{{outlet}} //It is a general helper, where content from other pages
will appear inside this section
使用以下代码打开在app/routes/下创建的文件willtransition.js文件 -
import Ember from 'ember';
export default Ember.Route.extend ({
actions: {
willTransition(transition) {
//decalring the self variable
var self = this;
//checking whether self variable is false or not
if (!this.get('allowTransition')) {
document.write('<b><font color = "red">');
//display the message
document.write("transition abort");
document.write('</font><br>');
transition.abort(); //calling abort function
Ember.run.later(function () {
//setting the self variable to true
self.set('allowTransition', true);
document.write('<b><font color = "blue">');
//display the message
document.write("transition retry");
document.write('</font>');
transition.retry(); //calling retry function
}, 500);
}
}
}
});
使用以下代码打开在app/templates/下创建的willtransition.hbs文件 -
<h2>Hello...Welcome to xnip!!!</h2>
{{outlet}}
输出 (Output)
运行ember服务器,您将收到以下输出 -
单击链接时,将显示数据。 但是如果单击后面的链接, willTransition操作将调用transition.abort()然后调用transition.retry()方法。