utilize require.js using data-main or require? - javascript

I have the following line in head.
<script data-main="{% static 'site_common/js/main.js' %}" src='{% static "site_common/bower_components/requirejs/require.js" %}'></script>
main.js has
require(['site_common/js/config'], function() {
});
at the bottom of body, I have
require(["site_common/js/config"], function () {
require(['infrastructure'], function () {
require([
'content_tab/apps/content-tab-app',
], function(ContentTabApp) {
var appOptions = {
el: "#ann-content-app",
contenttype: contenttype,
threads_obj: threads_obj,
thread_obj: thread_obj
};
var content_tab_App = new ContentTabApp(appOptions);
Backbone.history.start({
pushState: true,
hashChange: false
});
});
});
});
I had the first line (with data-main) because I thought it was required but now I think it is superplous.
But then if I remove that line, how would the page know that it needs to download require.js itself?

You are on track. In this case what you are trying to do is load require.js script and pass data-main attribute pointing to entry-point of your application which is main.js
However, there are several other patterns you should take a look at
<script data-main="{% static 'site_common/js/main.js' %}" src='{% static "site_common/bower_components/requirejs/require.js" %}'></script>
...then in your main.js
require(["site_common/js/config"], // dependencies 1st loaded
function () { // callback after dependencies above have loaded successfully
require(['infrastructure'], // this loads 2nd
function () { // after second nested dependency loaded this callback will be executed
require(['content_tab/apps/content-tab-app'], // this loads 3rd
function(ContentTabApp) { // after third dependency has loaded this function will be called
var appOptions = {
el: "#ann-content-app",
contenttype: contenttype,
threads_obj: threads_obj,
thread_obj: thread_obj
};
var content_tab_App = new ContentTabApp(appOptions);
Backbone.history.start({
pushState: true,
hashChange: false
});
});
});
});

Related

Laravel and VueJS, access Vue instance.

I want to change a data property and run a method on my Vue instance within Laravel. However due to using webpack and laravel I can't seem to access the instance how I would expect to:
So window.app doesn't appear to be the correct instance of my Vue class.
Below is the Blade View i'm loading, as you can see I append a script tag to my main layout.blade.php, simply trying to change the Vue instance data property, and run a method.
#push('scripts')
<script>
app.unsaved = true;
app.triggerEvent(null, 'models', null);
</script>
#endpush
Below is part of my app.js (resources/assets/js/app.js):
const app = new Vue({
el: '#app',
components: {
'models-select': ModelsSelect
},
data: {
showModel: false,
unsaved: false
},
mounted: function() {
let _self = this;
(function() {
document.querySelectorAll("input, textarea, select").forEach(function(e) {
e.addEventListener('change', function() {
_self.unsaved = true;
e.classList.add('is-changed');
});
});
function unloadPage(){
if (_self.unsaved) return 'You appear to have un-saved changes!';
}
window.onbeforeunload = unloadPage;
})();
},
methods: {
triggerEvent: function(event, target, property)
{
app.$refs[target].update(event, property);
}
As you can see i'd expect to manipulate the Vue instance through the global app variable I have defined within the app.js. However this doesn't appear to be the case.
I get the following error when running the triggerEvent method:
app.triggerEvent is not a function
In your app.js file, change const app = new Vue({ to window.app = new Vue({.
Then within your <script> tags, change it to this.
<script>
window.app.unsaved = true;
window.app.triggerEvent(null, 'models', null);
</script>

How to write Vue js code in separate file and include in laravel

How to write Vue js code in separate file and include in laravel
Blade page code?
Am also using gulp file.
#section('js')
<script>
new Vue({
// Defining a element.
el: '#branddashboard-html',
data: {
// Defining data variable.
brandStats: null
},
// On load functionality.
created: function () {
// Initializing method.
this.getData();
},
},
// Methods to implement.
methods: {
getData: function () {
self.brandStats = null;
$.get('brand-stats/' + userId + '/' + period, function (data) {
self.brandStats = data;
});
}
}
});
</script>
#endsection
I think this is no the best idea. I think, the Blade's Templates only works in the views folder. Your frontend logic is now managed with Vue Component System, in this MVVM vue way. Hope this be usefull to you

Applying RequireJS to a modular one page application

I actually have two questions concerning requirejs and singleton objects. I want to form a singleton object playing the role of my application core and pass it to modules as a parameter. How should this be done?
The other issue I have is related to a private object inside the application core. It's suppose to act as a container for modules but for some reason when I try to start the application, this container seems to have those modules but it can't be looped through. Any ideas why this is happening?
Here's an example code of the situation:
// applicationConfig.js
require.config({
baseUrl: 'js',
paths: {
jquery: 'jquery-3.1.1.min',
core: 'utils/applicationCore',
domReady: '../lib/domReady'
}
});
require(['modules']);
// modules.js
define(['core', 'domReady'], function(Core, domReady) {
require([
'modules/module1'
]);
domReady(function() {
var modules = Core.getModules();
var name = '';
for (name in modules) {
modules[name].creator(); // Start a module...
}
});
});
// applicationCore.js
define(function() {
return (function() {
var _modules = {};
return {
add: function(name, creator) {
_modules[name] = {
creator: creator
};
},
getModules: function() {
return _modules;
}
}
}());
});
// module1.js
define(['core', 'jquery'], function(Core, $) {
Core.add('module1', function() {
// Module constructor function.
});
});

Access module.exports from external file

I would like to view the contacts of a function from an external file.
MarionetteJS app.js file:
module.exports = functionToAccess = (function(superClass) {
extend(functionToAccess, superClass);
function functionToAccess() {
this.doSomething = bind(this.doSomething, this);
return functionToAccess.__super__.constructor.apply(this, arguments);
}
functionToAccess.prototype.defaults = {
someProperty: 'some value',
anotherProperty: 'another value',
canAccessThis: false,
wouldIlikeTo: true
};
[...]
return functionToAccess;
})(Wrapper);
In an external PHP file, I am trying to alert or console.log the contents of anything from the above file, but preferably the functionToAccess function.
External JS script inside PHP file:
// Using the RequireJS CDN here resolves 'require is undefined'
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js" type="text/javascript"></script>
var testFileLoad = require(['path/to/app'], function() {
});
console.log(testFileLoad);
This returns a localRequire function. How can I instead return functionToAccess?
You need to declare a variable in the callback function, which is where you will have access to your path/to/app code. Try something like this:
require(['path/to/app'], function(functionToAccess) {
functionToAccess(); // is available here
});

Confused with Backbone.js Paginator

I am trying to introduce pagination using the backbone.js paginator plugin's requestPager.
Problem: After setting up the collection which extends Backbone.Paginator.requestPager, I refreshed the webpage and the javascript console threw the error:
Uncaught TypeError: Object function (a){return new m(a)} has no method 'result' backbone.paginator.js:678
I am very new to backbone and is not sure what went wrong. Is it because I used fetch(), which showed up in the screenshot of the error below? I also noticed that no GET requests were sent to the backend. What happened, and how should I fix this? Thanks!
JS code
// Collection
window.ListingCollection = Backbone.Paginator.requestPager.extend({
model: Listing,
paginator_core: {
type: 'GET',
dataType: 'jsonp',
url: 'api/listings'
},
paginator_ui: {
firstPage: 0,
currentPage: 0,
perPage: 10,
totalPages: 10
},
server_api: {
'$filter': '',
'$per_page': function() { return this.perPage; },
'$current_row': function() { return this.currentPage * this.perPage; },
'$order_by': 'listing_id'
},
parse: function(response){
this.totalPages = Math.floor(response.total_rows / this.perPage);
}
});
JS Code
// Router
var AppRouter = Backbone.Router.extend({
routes: {
'': 'listings',
'listings': 'listings'
},
listings: function() {
var self = this;
// Load initial search results
this.listingList = new ListingCollection();
this.listingList.fetch({
success: function() {
self.listingListView = new ListingListView({ model: self.listingList });
$('#listing_list table').append(self.listingListView.render().el);
}
});
this.listingFilterView = new ListingFilterView();
}
});
Screenshot of Error in Javascript Console
JS Includes
<!-- JavaScript -->
<script src="assets/js/lib/jquery-1.7.1.min.js"></script>
<script src="assets/js/lib/underscore-min.js"></script>
<script src="assets/js/lib/backbone-min.js"></script>
<script src="assets/js/lib/backbone.paginator.js"></script>
<script src="assets/js/lib/bootstrap.js"></script>
<script src="assets/js/lib/bootstrap-datepicker.js"></script>
<script src="assets/js/app.js"></script>
You are probably using older version of Underscore. I use 1.3.1 and it does not have result() method. Download their new production version 1.3.3 - it has result().

Categories

Resources