0

Backbone.js+Require.jsでロールアウトしたいと思います。モジュールを問題なくロードできます。しかし、テキストを使用して.htmlファイルをロードしようとすると!プラグイン(text.js)、次のエラーが発生します:

スクリプトとして解釈されるが、MIMEタイプtext / htmlで転送されるリソース:" https://host.net/templates/login.html "。require.js:1843

キャッチされないSyntaxError:予期しないトークン<login.html:1

Uncaught TypeError:未定義のunderscore.js:1130のメソッド'replace'を呼び出せません

これが私が取り組んでいるものの仕様です:

ブラウザ:Chrome

サーバーサイド:PHP w / Slim

マシン:bitnami AMIを使用したAWSマイクロインスタンス//これらは本番環境のデフォルトが設定された状態で出荷されるため、Apacheの設定が正しくないか、php.iniが正しくない可能性があります。何がわからない。

ディレクトリ構造:

/
   dev/    // Webroot: Behind basic_auth for dev reasons
       web/
           index.php    // Starts up the Slim router and PHP backend 
               app/
                   app.html    // The entry point for our SPA, data-main defined here
       js/   // At root for module accessibility in case of reuse
           apps/
           app/
               main.js  // Here we do require.config and bootstrapping
           app.js   
           router.js
           text.js
           modules/
               models/
                   login.js
               views/
                   login.js
           lib/
                   backbone/
                   backbone.js
               jquery/
                   jquery.js
               require/
               require.js
               underscore/
               underscore.js
       templates/   // Also at root for access to reuseable markup, such as login.html
        login.html

これが私が関連すると信じているいくつかのコードです:

/js/apps/app/main.js

requirejs.config({
 baseUrl: '/js/apps/app',

  shim: {
    'backbone' : {
      deps: ['underscore', 'jquery'],
      exports: 'Backbone'
    },
    'underscore' : {
      exports: '_'
    },
    'jquery' : {
      exports: '$'
    },
    'backbone.ajaxcommands' : {
      deps : ['backbone', 'underscore', 'jquery'],
    }
  },

  paths: {
    jquery:     'lib/jquery/jquery-1.9.1.min',
    underscore: 'lib/underscore/underscore',
    backbone:   'lib/backbone/backbone-min'
  },

  config: {
    text: {
      useXhr: function (url, protocol, hostname, port)
      {
        protocol = 'https';
  //      return true; 
      }
    }
  }
});
require(['app'],function(App){
    App.initialize(); 
    App.start(); 
  }
); 

/js/apps/app/modules/views/login.js

define([
  'backbone',
  'underscore',
  'modules/views/login',
  'text!/templates/login.html'
], function(Backbone, _, Login, loginTemplate){
  var LoginView = Backbone.View.extend({
    el: $("#login-form"),

    events: {
      "click #login": "login"
    },

    template: _.template(loginTemplate),

    initialize: function(){
      var self = this; 

      this.username = $("#username"); 
      this.password = $("#password"); 

      this.username.change(function(e){
        self.model.set({username: $(e.currentTarget).val()});
      }); 

      this.password.change(function(e){
        self.model.set({password: $(e.currentTarget).val()}); 
      });

    },

    login: function(){
      var user= this.model.get('username'); 
      var pword= this.model.get('password'); 
      if(this.model.save() == false)
      {
        console.log("We got issues loggin' in"); 
      }
      else
      {
        console.log("We should have cookies now"); 
      }
    }

    //render: function(){
    //  this.$el.append(this.template); 
    //}
  });
  return LoginView; 
}); 

/templates/login.html

`<div>hi</div>`

解決策を見つけるために作業する: Chromeデバッガーを見ると、[ネットワーク]タブで、実際にlogin.htmlが取得されていることがわかりますが、chromeはそれをJSファイルと見なします。

ブレークポイントを使用してコードをステップ実行したところ、Require.js 1843で、その行のノードオブジェクトに、一連の属性を持つ''タグと等しい'outerHtml'という属性があることがわかりました。それで、おそらくそれは私のhtmlをタグで包んでいるのでしょうか?デバッガーの[ネットワーク]タブの[プレビュー]タブを見ると、実際にマークアップが表示されています。login.htmlに有効なjsコードがある場合、構文エラーは発生しません。ただし、HTMLの形式が正しくないため、underscore.jsエラーが発生します。

私はこれらの解決策を試しました: Chromeは「リソースはスクリプトとして解釈されますが、MIMEタイプtext / plainで転送されます」と言いますが、何が得られますか?

プロジェクトの下でjs/templateコードを移動します(パスを絶対ではなく相対にします)。すべてが機能しているように見えましたが、text.jsはlogin.htmlの最後に.jsを追加するため、404が見つかりませんでした。これは、明らかにクロスドメインアクセスが原因ですか?

baseURLの設定を含む、require.configを使用したさまざまな構成オプション

残念ながら私が忘れてしまった他のたくさんの微調整。これは本当に苛立たしいことです。

お時間をいただきありがとうございます。

編集:ドライブ で見ているのと同じ動作を示すスタンドアロンを配置しました。ファイル構造は次のようになります。

/
    index.html //This can actually be anywhere visible on the web
    so-js/
        ...
    so-templates/
        ...

so-js /とso-templatesがwebrootにあることに注意してください。インデックス・ファイルはどこにでも置くことができます。

4

2 に答える 2

6

この行が原因で問題が発生します。

   config: {
    text: {
      useXhr: function (url, protocol, hostname, port)
      {
        protocol = 'https';
      //  return true; 
      }
    }
  }

これはtext!のuseXhrメソッドをオーバーライドします。これは、ブール値を返して、テキストファイルのJavascriptバージョンが使用可能かどうかを判断することを目的としています。そうである場合はfalseを返し、そうでない場合はtrueを返します。

何も返さず、undefinedは偽物であるため、<script>タグでロードする必要があることを意味します。これが、MIMEタイプの警告とその後のエラーを受け取る理由です。

この構成プロパティ全体を削除すると、エラーがなくなり、loginTemplateがlogin.htmlに入力されます。

于 2013-02-20T00:47:42.930 に答える
0

また、 gruntを使用してhtmlテンプレートからモジュールを生成することもできます

このような:

テンプレート/hello.html

<div>hello world!</div>

js / templates / hello.js

define('templates/hello', '<div>hello world!</div>')

grunt task config:

function converTemplate(srcDir){
    return function(){
        grunt.file.recurse(srcDir, function(abspath, rootdir, subdir, filename){
            if(/^.*\.html$/.test(filename)){
                if(subdir){
                    subdir = subdir.replace(/\\/g, '/');
                }

                var content = grunt.file.read(abspath),
                    targetPath = 'js/templates' + '/' + (subdir ? subdir + '/': '') + filename.replace('.html', '.js'),
                    moduleName = 'templates/' + (subdir ? subdir + '/': '') + filename.replace('.html', '');
                content = content.replace(/[ \t]*\r?\n[ \t]*/g, '');
                content = content.replace(/'/g, '\\\'');
                content = "define('"+moduleName+"', [], '"+content+"');";
                subdir && grunt.file.mkdir('js/templates/' + (subdir ? subdir + '/': ''));
                grunt.file.write(targetPath, content);
            }
        });
    };
}

grunt.registerTask('template', 'conver template', converTemplate('templates'));

ディレクトリ構造:

templates/
    hello.html
js/
    templates/
        hello.js
于 2013-02-20T01:54:01.310 に答える