View instantiating another view - separation-of-concerns

I'm separating my code similar to MVC (models, views, and controllers).
Let's say I have two view classes, one is conceptually a page (contains many items) and another is just a widget (like a list of recent news).
Here are the ways I see of doing it:
The controller instantiates both the page and widget classes, then passes the widget object into the page. If the page has a lot of widgets, I'd have to figure out how to pass it all in without it being confusing.
class PageController {
function foo() {
Widget widget1 = new Widget();
Widget widget2 = new Widget();
Page page = new Page(widget1, widget2);
}
}
class Page {
function Page(Widget widget1, Widget widget2) {
//do something with the widgets
}
}
The page instantiates the widget class. But now the page class has references to all sorts of views instead of being able to place the view where ever as long as it has the appropriate interface.
class PageController {
function foo() {
Page page = new Page();
}
}
class Page {
function Page() {
Widget widget1 = new Widget();
Widget widget2 = new Widget();
//do something with the widgets
}
}
Something else?
What is your advice and why?
Thank you.

I actually side with approach 1 in some ways. I would say Page should be able to be instantiated with or without widgets. You can add a collection of widgets to begin with and/or one at a time through some other provision within the Page as you run through your business logic and rules.
This gives you more flexibility to modify the construction of page as you go.
Widgets contain information on how they function and their presentation within the layout of the page.
Page should only be responsible for getting the information/instructions from the contained widgets and initialize/render them.
This will allow for a more flexible and fluid design.

Conceptually, #2 makes the most sense to me.
It's perfectly fine to have coupling between views if one type of view contains another. For example, it should be the page's job to manage where to place each widget, when to hide certain widgets etc.
However, the page shouldn't care about events pertaining to those widgets unless it needs to. If a widget has a button, it should just callback to a controller and skip telling the page... unless it causes the widget to be resized and the page needs to lay things out differently.
Hopefully this is useful to you.

Related

Building a new static html view by selecting a new request in the language menu

When developing a multi language website in ASP.NET, I read a lot of things like; routing, localization and CultureInfo. My basic knowledge about ASP.NET with MVC5 doesn't allow to go through with these advanced skills. As well, the project for this restaurant, doesn’t need to be that advanced. It just need to load the correct language request with the new static html from the selected language through a new HomeController or whatever is needed.
My Project is currently online and when selecting French a new Index is loaded >>https://www.grandcafelamot.be/Language/Change?LanguageAbbrevation=fr. The same Index is been loaded for 'Nederlands', but this an issue I should solve later, I guess. But as I said, my main problem for the moment is, when selecting a language in the topbar language menu. From where can I build up a new Index and render it with the prober Body.
A second thing is that you've maybe noticed, I was capable to translate the topbar menu by resources when selecting French. Though, when clicking by example on Service-FR I am not able to load the new request Index with the correct language of this Link (Service-FR).
I've been searching so much to find a simple solution.
Thank you for reading my post and may be put me on the right way.
I'm not sure this is what you want. But you can return a different View based on a language setting. Then you simply need to create an additional cshtml file in the correct language, in this case the index-fr.cshtml.
public ActionResult Index()
{
var model = new Models.HomeViewModel();
if (MijnTaal == "nl-NL")
{
return View(model);
}
else
{
return View("index-fr", model);
}
}
Or write a simple method for it so you do not need to write those if/else statements every time.
public string getAction()
{
string action = ControllerContext.RouteData.Values["action"].ToString();
if (MijnTaal == "nl-NL")
{
return action;
}
else
{
return action + "-fr";
}
}
And then
return View(getAction(), model);

Pros and Cons of creating a separate class for the GUI (in actionscript)

This is related to a similar question I just asked; however, this one is specifically tailored to my individual project, rather than object-oriented programming in general.
I am working on a version of hangman with some interesting programming twists. I don't need to go into detail of what they are as the logic for the game is already finished. I can run an entire game by hard-coding variables for the user input (such as guess selection). I am now in the process of replacing all those bits that require user interaction with the trappings of an actual game like buttons, images, sounds, etc.
I am trying to figure out whether it is better to have all of this stuff be part of my main class, or whether I should create another class to handle it all. For example, I want my players to be able to click on an on-screen keyboard to make their guess, with each button firing a separate event listener call to the makeGuess function. Would it be better to create the buttons as direct children of my main game class, or should I create a subclass (called Keyboard, for example) that creates the keyboard section of the board with the appropriate events, then add the keyboard class as a child to the main rather than all the pieces? What are the pros and cons of each of these choices?
For the record, I'm programming using FlashDevelop, so nothing like a timeline for me.
I say you'd better create at least the Keyboard class that will parse the events fired by tapping/clicking keys inside, and give it a callback reference to your Main class, or GameLogic class, so that it can do theMain.guess(letter); and then the Main class logic will come to life and process the callback. Since this structure is not exactly related to game logic, and technically it can then be reused by implementing an interface for the callback, so that you can use this keyboard elsewhere where you want to have your player to type letters using mouse, it's better be separated from main logic.
public class Keyboard extends Sprite {
public var callback:AcceptingKeys; // an interface
... // class implementation, with all the listeners, children and stuff
// and you call in there: callback.acceptKey(key);
}
public interface AcceptingKeys {
public function acceptKey(key:String):void; // or whatever type you need
}
And you do with your Main class:
public class Main extends Sprite
implements AcceptingKeys {
...
var keyboard:Keyboard;
private function init(e:Event=null):void {
... // other code. It's FD, then this function exists
keyboard=new Keyboard();
keyboard.callback=this;
// past this point your instances can talk
}
public function acceptKey(key:String):void {
// match interface description
... // do game logic for parsing a key
}
}

use class to handle mutiple nested movieclips and their specific events

I have a menu with five buttons. Menu is visible all the time. there is click event for each menu item. which slides corresponding movie clip from left to right. each movie clip has different nature events and respective animation and activity. for example tab 1 brings the video page. and within that movie clip I have video events like play pause volume and on complete etc. events and code. tab 2 has button group for Time and another button group Features. depending on user selection code will calculate and show value on a animated counter. tab 3 has button group for Time and button group Source. as per the user selection it will calculate and show the values as animated graph. and so on.
Right now I have all the individual tab movie clip has its own time line code for its own events. and some crossover variables and references with other tabs. Everything is working as expected. No problem. I know time line code is not the best way to do any complex project.
So, I would like to get the entire coding as one class or more classes if that is the correct way.
I am beginner as far as class logic. I have already created Main as document class and could control the general navigation of tabs and their initial look. But stuck at tab specific button events and other such unique events for the specific tab.
Any help is greatly appreciated. Thanks in advance.
any similar example or suggestions.
First of all, thanks a lot for a prompt response. It seems like I am not even a beginner. I need to read a lot and probalbly grasp all fundamental concepts thoroughly. I have gone through both the links suggested in your comments. I am trying to digest the stuff slowly. I do not have any formal informal education regarding OOP or any sort of programming. To be honest, I have hard time understanding the code you have suggeted. Not because of your code but because of my level of caliber. I will have to spend some time to make myself clearer regarding events and sequence etc. different tab contents are as movieclips to main timeline and already placed on stage. It comes and goes to its corresponding tab button click event. I am not marking your answer as yes because I still need to my own homework based on your suggestion. Thanks a lot once again. I am sure I will ask few more questions later.
This is how I would design it:
I'd have a Menu Class, which only contains the buttons and "converts" clicks on them into more specific events. That might look something like this:
public Class Menu extends Sprite {
protected var buttons:Vector. = new Vector.();
public function Menu() {
super();
var loops:int = numChildren;
for (var i:int=0; i<loops; i++) {
var button:SimpleButton = getChildAt(i) as SimpleButton;
if (button) {
buttons[buttons.length] = button;
button.addEventListener(MouseEvent.CLICK, broadcastMenuEvent);
}
}
}
public function broadcastMenuEvent(e:Event):void {
var button:DisplayObject = e.currentTarget as DisplayObject;
dispatchEvent(new Event(button.name, true));//bubbling, can catch at any level
}
}
The way this is built, you can change the events that are being dispatched simply by changing the name you give the instance of the button on stage. Note that you need to apply Menu as the Base Class and not the Class for this to work if you have "declare instances automatically" unchecked, because doing it that way allows the compiler to generate those instance names for you in a way your base Class doesn't have to know about.
At this point, you can then deal with those events in another place--whether it's your main document Class or whether you have a separate Controller.
I would define each of the Views you described as a separate Class as well. If you have objects coming and going on the stage, you can use one of the techniques described here to handle that. Otherwise, it's fairly straightforward to address your timeline instances from the base Class instead of timeline code. Again, you can listen for those events in the main document Class or a dedicated Controller--the main point is to make sure your Views are not making any important decisions and usually they should not be editing data.
You can choose to have your Main Document orchestrate how the tabs get added and removed (I'm a big fan of using the timeline with goToAndStop, but not everyone shares this preference), or, again, you can separate this logic out to a dedicated Controller. I would suggest that if it's possible to generalize how your Views work to have them implement a single Interface. That way, you can give them a single instance name and manage them all with the same getter/setter pair (assuming you go the timeline route).
Note the Flash compiler isn't terribly sophisticated in this regard, so if you do this and your Views extend different parent Classes, you'll get compiler warnings. Just ignore these--they don't mean anything.
The thing you shoud try to root out of your code completely is the part where Views are referencing each other. The only time it's acceptable for one View to know about another is when it's a parent knowing about its child. Even then, try to have as little specific knowledge as possible. Notice in the Menu View I wrote as an example, the parent only knows there may be some SimpleButtons, but it has no specific knowledge of where they are on stage, what, specifically, is in them, or even what there instance names are.
Instead of having your Views know about one another, have a third party (which, again, you can choose to use the main Document Class for or not) that transfers requests for state changes (in the form of events) from one to another.

Wordpress―run JS after Widget was created in Admin panel

I am developing a Wordpress Theme that includes a custom Widget, everything works out fine but there is one thing I do not know how to implement correctly:
I would like to run some Javascript after the Widget Instance was created in the admin panel, that means in the very moment after the widget was dropped in a sidebar, not after saving.
I have no Problems with running JS after the page was loaded or the Widget was saved, I want to run Javascript after the User just dropped a new Instance into the side bar, what actually can happen more than once without page reload.
Greetings philipp
Another way of doing this I just figured out --
I'm going to show a more complex example involving dependencies, though realise the bit in Custom_Widget::form() is the real answer to the question:
function add_js_deps() {
if (is_admin()) {
wp_enqueue_script('jquery-ui-accordion');
}
}
add_action( 'init', 'add_js_deps' ); // "init" because wp_enqueue_scripts is too late.
// Then in the widget....
class Custom_Widget extends WP_Widget {
public function form($instance) {
/** Collapsing accordion-y form HTML here **/
wp_enqueue_script('custom-js', plugins_url('js/my.js', __FILE__), array('jquery-ui-accordion'), '1.0.0', true);
}
}
I'd argue this is the better route as it has dependency management and you won't have a bunch of JavaScript mid-way into your DOM. Using wp_enqueue_script is generally always the more WordPressian way of doing things regardless.
Place a script tag in the widget form function.
function form($instance)
{
?><script type="text/javascript">console.log("firing javascript");</script>
<?php
//form details...
}
I eventually went a different way with this. Loaded our plugin admin script on the page using wp_enque_script and then just used jquery selectors and an event handler to target the right widget.
$('div.widgets-sortables')
.on('sortstop', function (event, ui) {
// only if this widget has the proper identifier...do something
if (ui.item.find('.my_widget').length == 0)
return;
run some function...
Still not my favourite technique...but it is cleaner then coding it in the widget. Does require a variable to track created widgets and using the "this" variable is useful

AS3 game element structure

I'm trying to figure out how best to setup a kind of universal game element class for my game. What I want to try and create is a structure similar too..
GameElementPositionMovement (root class)
->GameElementVisual (handles all the graphics)
->GameElementPersonality (handles game logic)
I then want to be able to set up different personalities (monster, hero, icon etc) just by creating an instance of GameElementPersonality, but in it's constructor also be able to setup the visual and positioning/movement aspects as well.
I mentioned this in another question, and the answer that came back was...
It seems that you need kind of 'data model' class to store logic and a
visual ('view') class. Visual class shouldn't inherit from data model,
it should use it. This is OOP related problem: IS vs HAS (inheritance
vs composition)
But I'm not sure if I understand that. The position/movement without any visual data, seems a good first root class, and then you add to that the visual aspects (GameElementVisual), and then finally you add in personality "traits" (GameElementPersonality) such as armour, damage, health etc
Therefore I'm keeping, the positioning/movement, visual and logic separate, and I presumed the heirachy that I've laid out would be the best way to do that, but is this not a good way to do this? should it be more flat? with the GameElementPositionMovement, creating both a visual and logic instance and storing that in itself?
You could create a structure similar to this:
(pseudocode)
ElementData
//it doesn't have to extend any particular class
//however it would be nice if it could dispatch events and register listeners
class ElementData implements IEventDispatcher
{
public function ElementData() //constructor
{
//do some stuff
}
public function setSomeProperty(value:int):void
{
//
}
public function doSomeCrazyStuff():void
{
//
}
}
ElementVisual
class ElementVisual extends MovieClip //or just Sprite or even DiplayObjectContainer
{
public function ElementVisual(elementData)
{
//constructor takes an instance of ElementData class
elementData.addEventListener(CHANGE, onDataChange)
elementData.doSomeCrazyStuff();
if (userCliked)
{
elementData.setSomeProperty(15);
}
//you can have here some interactions with user (keyboard, mouse)
//then it can communicate with elenemtData and 'listen' what it says.
}
function onDataChange
{
//react accordingly
}
}
some visual representation (you may need many of these)
class Monster extends ElementVisual
{
//do all the graphic, animations etc
}
Then you need a class to set up all the data, visuals etc… In simplest implementation it can be the 'document class'.
It's not a proper MVC model - it's a simple example to show the concept of decoupling logic from visualisation.
MVC is not the only solution, there are other so called 'design patterns' which may be useful...
Yeah the idea with MVC is to keep things decoupled, in your case you're ultimately smashing everything into one chain of inheritance where you'll end up with one type of object that inherits all the properties from another object that inherits all the properties from another object, so you'll have an instance of this thing that represents everything, which is why this isn't a great pattern to go with.
If instead you have a GameElementPositionMovement class (Your main class) create an instance of the GameElementVisual and in instance of GameElementPersonality (or multiple instances if need be). Then any time a change to a property is made in GameElementPersonality (or any in the collection if you choose to make a collection) could dispatch an event, the main class GameElementPositionMovement could listen for the dispatched event and when it gets it can set/pass the GameElementPersonality instance or array to the GameElementVisual. Then in the GameElementVisual you're just dealing with drawing based on the current model all the time, the model is separated from the view logic, you'd also probably want to handle control in a separate class or in GameElementPositionMovement. (control being the modification of the model, in this case it would probably also be where you register listeners for user events, keyboard, mouse whatever)
This way the model remains clean of control logic and view logic, it's a clear separation of what goes where and really only the view sort of depends on the model and the controller sort of depends on the view but if interfaces are established for what the model view controller each need to communicate with each other in this way you can swap out any of those parts with a new class that implements the interface (not likely an issue in a small game, but the design lends itself to this ability and therefor future scalability).