1

我在需要时使用 Asp.net MVC 来拉取我的页面。我的页面结构是:

{
   Layout = "";
}

  <div data-role="page"> 
     ....


      <script type="text/javascript">
        $(document).one("pageinit", function () {

          ....
      </script>

  </div>

我应该像上面那样保留我的页面结构,还是应该将我的脚本放在一个全局外部 javascript 文件中(在这种情况下,我如何将每个“pageinit”与正确的页面相关联)?

我遇到的另一个问题是在 chrome 中调试嵌入式脚本。这与它嵌入的事实有关吗?

4

2 回答 2

0

This is what I have done;

Firstly, I have all my scripts that I will ever need in one external JS file.

In my MVC layout page I have created the div for the data-role wrapper to set its id attribute from a property each and every controller action will return with a unique value.

The layout page.

<body class="ui-mobile-viewport">
    <div data-role="page" id="@ViewBag.PageId">

Then in my Controller Action I return a unique value to the view;

public ActionResult Index()
        {
             ViewBag.PageId = "pageCustomers";

            return View();
        }

This means that I can bind to the page.init event as follows. The script below is wrapped in <script> tags in the in the MVC view that the controller returns and allows custom JS code for that particular view to be fired when the view has loaded.

 $('#pageCustomers').live('pageinit', function (event) {
    // do something
}
于 2012-08-20T05:28:36.627 回答
0

如果您移动到单个 JS 包含,我建议这样做,那么您将更容易维护代码,因为它会在一个地方。

pageinit您可以根据正在初始化的伪页面的 ID运行代码:

//setup initialization code for each pseudo-page that needs it
var myCode = {
    someID : function (event) {
        //run initialization code for the pseudo-page with the ID of "someID"
    },
    someOtherID : function (event) {
        //run initialization code for the pseudo-page with the ID of "someOtherID"
    }
};

//setup a delegated event handler for each pseudo-page's "pageinit" event
$(document).on('pageinit', '.ui-page', function (event) {

    //check if a function for this pseudo-page exists
    if (this.id in myCode) {

        //since the function exists, call it and pass "this" as the current pseudo-page as well as passing-in the "event" object
        myCode[this.id].call(this, event);
    }
});
于 2012-08-17T22:12:16.447 回答